JSONP跨域 (百度为例)
由于Ajax请求不支持跨域,多个域名交互就会有问题。 跨域的原理是这样的,在html中的src属性请求的地址是可以跨域的,比如<img >和<script> 比如 test.js中 test({name:'meigong',sex:'man'}); index.html中
- <script>
- functiontest(data){
- alert('姓名:'+data.name+"性别:"+data.sex);
- }
- </script>
- <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 举报,一经查实,本站将立刻删除。