JSONP跨域


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

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

比如 test.js中

test({name:'meigong',sex:'man'});
index.html中

<script >  
  
function test(data){  
  
alert('姓名:'+data.name+"性别:"+data.sex);  
  
}  
  
</script>  
<script src='http://www.biuman.comt/test/test.js'></script>  
这时候会弹出框,越狱成功!


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


<script>  
  
//回调函数  
function test(a){  
   alert(a.name);  
}  
setTimeout(function(){  
    var url ="http://www.biuman.com/test/jsonp/test.php?cb=test";  
    var script =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

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


<script type="text/javascript" src="http://sources.ikeepstudying.com/js/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
  $.getJSON("http://test.ikeepstudying.com/json.php?callback=?",
  function(result) {
    for(var i in result) {
      alert(i+":"+result[i]);//循环输出a:1,b:2,etc.
    }
  });
</script>

原文地址:https://www.cnblogs.com/qiandu/p/4281000.html