加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

JSONP跨域 (百度为例)

发布时间:2020-12-16 19:14:17 所属栏目:百科 来源:网络整理
导读:JSONP跨域 (百度为例) 2013-01-31 由于Ajax请求不支持跨域,多个域名交互就会有问题。跨域的原理是这样的,在html中的src属性请求的地址是可以跨域的,比如img 和script比如 test.js中test({name:'meigong',sex:'man'});index.html中 view plain copy to c

JSONP跨域 (百度为例)

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

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

比如 test.js中

test({name:'meigong',sex:'man'});
index.html中
view plain copy to clipboard print ?
  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/

    (编辑:李大同)

    【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

      推荐文章
        热点阅读