跨域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 使用
原生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