跨域JSONP實質(zhì)與JavaScript實現(xiàn)

跨域JSONP實質(zhì)與JavaScript實現(xiàn)

實質(zhì)

利用script標(biāo)簽的src屬性(瀏覽器允許script標(biāo)簽跨域),通過動態(tài)創(chuàng)建一個script標(biāo)簽,指定src屬性為跨域的api,那么html會把返回的字符創(chuàng)當(dāng)作javascript代碼來進(jìn)行解析,如果我們在返回的字符串中使用自定義函數(shù)形式包裝起來,然后在html中調(diào)用自定義函數(shù),即可拿到返回的字符串。

jQuery 使用

jQuery.getJSON 官方文檔

原生js實現(xiàn)

getJSONP

【實現(xiàn)】

var getJSONP = function(url, callback) {
  //動態(tài)生成回調(diào)函數(shù)名并定義回調(diào)函數(shù)
  var cbname = 'jsonp' + (new Date()).getTime();
  window[cbname] = function(response) {
    try {
      callback(response); //處理響應(yīng) 
    } finally {//清理工作
      delete window[cbname];
      script.parentNode.removeChild(script);
    }
  }
  //動態(tài)添加script
  var script = document.createElement("script");
  script.src = url + cbname;
  document.body.appendChild(script);
  //請求成功
  script.onload = script.onreadystatechange = function() {
    if (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") {
      alert('Loading successful');
      script.onload = script.onreadystatechange = null;
    }
  }
  //請求失敗;IE 低版本不支持onerror,并且在加載失敗時執(zhí)行成功事件。
  script.onerror = function() {
    alert("Loading failed");
  }
}

【使用】

var url = "http://127.0.0.1:9999/jsonp";
getJSONP(url + "?callback=", function(data) {//這里需要跟服務(wù)端協(xié)調(diào)好名字 比如callback或者jsoncallback等等
  alert(data);
});

拓展

如果想全部瀏覽器兼容的話,在條件允許的情況下可以參考

How to trigger script.onerror in Internet Explorer?--stackoverflow

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容