天天看点

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')[].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>