jsonp跨域具体实现

博主以前觉得只要知道jsonp是通过src属性来实现跨域的就行了,但是,发现最终吃亏的永远是自己,于是博主准备从今天开始,不再只是涉猎,应该去好好品尝其中滋味~

  1. 首先要明确客户端与服务器端通信的原理:
    如下:本地的程序通过script标签请求服务器端的文件

    <html>
      <body>
        <script src="http://remoteserver.com/remote.js"></script>
        <script type="text/javascript">
          var localHandler=function(data){
            console.log(data.result);
          }
        </script>
    
      </body>
    </html>

    remote.js
    服务器端调用客户端的函数

    localHandler({
      "result":"服务器端信息"
    })
  2. 知道如何通信之后,如何动态创建一个访问服务端的请求呢?
    当然就要涉及动态创建script标签,创建完了记得加入到文档中去哦

    <html>
      <head>
    
      </head>
      <body>
        <script>
          var handler=function(data){
            console.log(data.price);
          };
          var url="http://a.com/1.aspx?code=11&callback=Handler";
          var script = document.createElement('script');
          script.setAttribute('src',url);
          document.getElementByTagName('body')[0].appendChild(script);
        </script>
      </body>
    </html>
  3. jquery又如何使用jsonp跨域呢?
    首先在jquery中,jsonp是归于ajax的,而且会自动生成回调函数

    <html>
      <body>
        <script src="jquery.min.js"></script>
        <script type="text/javascript">
          jQuery(document).ready(function(){
            $.ajax({
              type:"get",
              async:false,
              url="http://a.com/1.aspx?code=11&callback=Handler",
              dataType:'jsonp',
              jsonp:"callback",
              jsonpCallback:'Handler',//此处可以不写,jquery会自动声生成函数,帮你处理数据
              success:function(json){
                console.log(json.price);
              },
              error:function(){
                alert('error');
              }
            })
          })
        </script>
      </body>
    </html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值