JSONP跨域 (百度为例)

JSONP跨域 (百度为例)

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

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

比如 test.js中

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

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

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

  1. <script >  
  2.   
  3. //回调函数  
  4. function test(a){  
  5.    alert(a.name);  
  6. }  
  7. setTimeout(function(){  
  8.     var url ="http://www.biuman.com/test/jsonp/test.php?cb=test";  
  9.     var script =document.createElement('script');  
  10.     script.setAttribute('src', url);  
  11.     document.getElementsByTagName("body")[0].appendChild(script);  
  12. },100);  
  13. </script >  
  1. test.php  
  2.   
  3. <?php  
  4. $filename = './su';  
  5. $fun = $_GET['cb'];  
  6. $arr=array(  
  7. 'name'=>'meigong',  
  8. 'sex' =>'man'  
  9. );  
  10. $res = json_encode($arr);  
  11. $res = $fun." (".$res.")";  
  12. file_put_contents($filename,$res);  
  13. header('Content-type: biuman/test');  
  14. header('Content-Disposition: attachment; filename='.$filename);  //下载模式,firebug的网络 中响应看不到内容  
  15. readfile("$filename");  
  16. exit();  
  17. ?>  

此外,jquery 也封装了jsonp

  1. <script >  
  2. $(function(){  
  3.     $.ajax({  
  4.          url: "http://www.biuman.com/test/jsonp/test.php",  
  5.          dataType: "jsonp",  
  6.          jsonp: "cb"//  
  7.          //传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback)  
  8.         jsonpCallback:"test"//需要的回调函数  
  9.          success: function(data){  
  10.                 alert(data.name);  
  11.          },  
  12.         error: function(){  
  13.             alert('网络异常');  
  14.         }  
  15.     });  
  16. })  
  17. </script >  

原创文章 转载请注明 来自美公网天下

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值