本文實作一個同時支援傳統 XHR 與 JSONP 兩種模式的跨域請求包裝函式,把底層差異收在內部,呼叫端只需要給定組態。
// 定義一個同時支援 XHR 與 JSONP 的請求模組
(function () {
if (typeof window.$JSON === 'undefined') {
window.$JSON = {};
}
$JSON._ajax = function (config) {
config = config[0] || {};
this.url = config.url || '';
this.type = config.type || 'xhr'; // 'xhr' 或 'json'
this.method = (this.type === 'json') ? 'GET'
: (config.method || 'GET').toUpperCase();
this.param = config.param || null;
this.callback = config.callback || {};
this.XHR = null;
if (typeof window._$JSON_callback === 'undefined') {
window._$JSON_callback = {};
}
this._createRequest();
};
$JSON._ajax.prototype = {
// 建立 XHR 物件,並把成功的建構方式快取下來,下次不必重複嘗試
_createXHR: function () {
var methods = [
function () { return new XMLHttpRequest(); },
function () { return new ActiveXObject('Msxml2.XMLHTTP'); },
function () { return new ActiveXObject('Microsoft.XMLHTTP'); }
];
for (var i = 0, l = methods.length; i < l; i++) {
try {
methods[i]();
} catch (e) {
continue;
}
this._createXHR = methods[i];
return methods[i]();
}
},
// 依 type 決定走哪一條路
_createRequest: function () {
return (this.type === 'json')
? this._setJSONRequest()
: this._setXHRRequest();
},
// 把 param 物件序列化成查詢字串
_serialize: function (param) {
var pairs = [];
for (var i in param) {
if (param.hasOwnProperty(i)) {
pairs.push(i + '=' + param[i]);
}
}
return pairs.join('&');
},
_setXHRRequest: function () {
var _this = this;
var param = this._serialize(this.param);
this.XHR = this._createXHR();
this.XHR.onreadystatechange = function () {
if (_this.XHR.readyState === 4 && _this.XHR.status === 200) {
_this.callback.success(_this.XHR.responseText);
} else if (_this.XHR.readyState === 4) {
_this.callback.failure && _this.callback.failure(_this.XHR.status);
}
};
this.XHR.open(this.method, this.url, true);
this.XHR.setRequestHeader(
'Content-Type', 'application/x-www-form-urlencoded; charset=utf-8'
);
this.XHR.send(param);
},
// JSONP:動態插入 script 標籤,避開同源政策
_setJSONRequest: function () {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
var fun = this._setRandomFun();
var _this = this;
script.type = 'text/javascript';
script.charset = 'utf-8';
(head || document.body).appendChild(script);
// 在頁面中定義回呼函式,收到資料後清理痕跡
window._$JSON_callback[fun.id] = function (data) {
_this.callback.success(data);
setTimeout(function () {
delete window._$JSON_callback[fun.id];
script.parentNode.removeChild(script);
}, 100);
};
script.src = this.url + '?callback=' + fun.name +
'&' + this._serialize(this.param);
},
// 產生不重複的隨機回呼函式名稱
_setRandomFun: function () {
var id = '';
do {
id = '$JSON' + Math.floor(Math.random() * 10000);
} while (window._$JSON_callback[id]);
return {
id: id,
name: 'window._$JSON_callback.' + id
};
}
};
window.$JSON.ajax = function () {
return new $JSON._ajax(arguments);
};
})();
var ajax = new $JSON.ajax({
url: 'https://www.sina.com/api',
type: 'json', // 走 JSONP
method: 'get',
param: { bar: true },
callback: {
success: function (data) {
console.log(data);
},
failure: function (error) {
alert(error);
}
}
});
為什麼要快取 _createXHR。三個建構方式依序嘗試後,把成功的那一個覆寫回 _createXHR,後續請求就不用每次都從頭 try-catch,這是一個便宜有效的小優化。
隨機回呼名稱必須做去重。_setRandomFun 用 do-while 檢查 _$JSON_callback 上是否已存在同名鍵,避免多個並發請求互相覆寫。
JSONP 的本質與限制。JSONP 靠的是動態插入 <script>,因此只能發 GET、無法設定自訂標頭,也不回傳真實的 HTTP 狀態碼——這代表 錯誤處理幾乎是空的:伺服器回 500 或回傳格式跑掉,前端通常只會静默失敗,甚至卡在 callback 從未被呼叫的狀態。要改善就得加逾時計時器自行判定失敗。
安全性。JSONP 相當於自願把目標網域的執行權引入自己的頁面,因此回呼端點必須完全可信。若要在正式環境處理跨域,優先考慮 CORS;若資料敏感,則應由後端代理而非在前端直接跨域。
另外,範例中的 _serialize 未做 URL 編碼,中文或特殊字元參數會出問題,實用時應補上 encodeURIComponent。
希望本文所述對理解 JavaScript 跨域請求機制有所幫助。