實現 javacript JSONP 跨域

0.跨域

有時咱們須要用AJAX來加載另外一個網站的數據,但AJAX不支持,必須尋找另外一種方法。Web頁面上調用js文件時則不受是否跨域的影響(不只如此,咱們還發現凡是擁有"src"這個屬性的標籤都擁有跨域的能力,好比<script>、<img>、<iframe>);javascript

1.什麼是JSONP

利用javascript動態建立<script>,並設置新的src來實現跨域,因此JSONP產生。JSONP是一種利用JSON格式傳輸跨域數據的一種格式。JSONP必須搭配服務端程序才能完成:1.直接請求你本身的服務器,服務器而後訪問其餘站點數據,而後返回;2.能夠直接訪問公開的JSONP服務器接口。html

如:Digg API:http://services.digg.com/stories/top?appkey=http%3A%2F%2Fmashup.com&type=javascript&callback=?前端


    Geonames API:http://www.geonames.org/postalCodeLookupJSON?postalcode=10504&country=US&callback=?java


    Flickr API:http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?jquery

2.前端代碼

(function (window) {

  var callBackHandler = function(data){ 
     alert(data.test); 
  }; 
  window.callBackHandler = callBackHandler; 
  function CD(){ 
  } 
  CD.prototype.getScript = function(){ 
          var scriptId = "callBackScriptId"; 
          var script = document.getElementById(scriptId) 
          if(script != null){ 
             script.parentNode.removeChild(script); 
          } 
          script = document.createElement('script'); 
          script.id = scriptId; 
          document.getElementsByTagName('head')[0].appendChild(script); 
          return script; 
  }

   CD.prototype.getURL=function(words){ 
       var callBackHandlerName = "callBackHandler";

       return "http://xxx.com?callback="+callBackHandlerName; 
  } 
   CD.prototype.getData=function(words){ 
    var s = this.getScript(); 
    s.setAttribute("src",this.getURL(words)); 
  } 
  window.cd = new CD();

})(window);

 

//調用cd.getData();

3.後端代碼(asp.net)

string callback = context.Request["callback"];
        if(callback == null || callback.Length == 0){
            callback = "callback";
        }
        context.Response.ContentType = "text/plain";
        context.Response.Write(callback + "({\"test\":\"hello world\"})");

4.jQuery 實現JSONP

jQuer很早就支持JSONP了,用起來很方便,以下: ajax

$.ajax({
             url:'http://xxx.xxx/xx.xx',
             dataType:"jsonp",
             jsonp:"jsonpcallback",
             success:function(data){
                //deal
             }
    });json

可參考:http://www.cnblogs.com/cfanseal/archive/2009/05/19/1460382.html後端

5.參考

http://www.cnblogs.com/dowinning/archive/2012/04/19/json-jsonp-jquery.html#!commentsapi

相關文章
相關標籤/搜索