微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

JSONP跨域 百度为例

JSONP跨域 (百度为例)

2013-01-31
由于Ajax请求不支持跨域,多个域名交互就会有问题。

跨域的原理是这样的,在html中的src属性请求的地址是可以跨域的,比如<img >和<script>

比如 test.js中

test({name:'meigong',sex:'man'});
index.html中
  1. <script>
  2. functiontest(data){
  3. alert('姓名:'+data.name+"性别:"+data.sex);
  4. }
  5. </script>
  6. <scriptsrc='http://www.biuman.comt/test/test.js'></script>

这时候会弹出框,越狱成功!

下面做个封装,把回调的函数名传递过去 模仿百度

//回调函数
  • functiontest(a){
  • alert(a.name);
  • }
  • setTimeout(function(){
  • varurl="http://www.biuman.com/test/jsonp/test.PHP?cb=test";
  • varscript=document.createElement('script');
  • script.setAttribute('src',url);
  • document.getElementsByTagName("body")[0].appendChild(script);
  • },100);
  • </script>
  • test.PHP
  • <?PHP
  • $filename='./su';
  • $fun=$_GET['cb'];
  • $arr=array(
  • 'name'=>'meigong',
  • 'sex'=>'man'
  • );
  • $res=json_encode($arr);
  • $res=$fun."(".$res.")";
  • file_put_contents($filename,$res);
  • header('Content-type:biuman/test');
  • header('Content-disposition:attachment;filename='.$filename);//下载模式,firebug的网络中响应看不到内容
  • readfile("$filename");
  • exit();
  • ?>
  • 此外,jquery 也封装了jsonp

    $(function(){
  • $.ajax({
  • url:"http://www.biuman.com/test/jsonp/test.PHP",
  • dataType:"jsonp",248)"> jsonp:"cb",//
  • //传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般认为:callback)
  • jsonpCallback:"test",0)">//需要的回调函数
  • success:function(data){
  • alert(data.name);
  • },248)"> error: alert('网络异常');
  • });
  • })
  • </script>
  • 原创文章 转载请注明 来自美公网天下

    本文的链接地址是:http://www.biuman.com/2013/01/jsonp-example-html/

    版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

    相关推荐