Web 2.0 時代,Ajax 是前端工程師的必修課,但瀏覽器的同源政策不允許跨域溝通,JSONP 就是最主流的變通方案。
jQuery 裡只要把 $.ajax 的 dataType 設成 jsonp 就能用,但 JSONP 和 Ajax 在實作原理上毫無關聯——它靠的是 script 標籤可以連結遠端 URL 這個特性:
<script src="https://jsonp.js?callback=xxx"></script>
callback 指定了一個函式名稱,遠端服務在輸出資料時呼叫這個函式並把資料當參數傳進來,跨域資料傳遞就完成了。
網路上不少範例寫得過於簡陋,直接用在專案裡會漏東漏西。下面把整個流程封裝成一個物件,可直接投入實務。
var JSONP = {
// 取得當前時間戳
now: function () {
return (new Date()).getTime();
},
// 取得 16 位隨機數
rand: function () {
return Math.random().toString().substr(2);
},
// 刪除節點元素
removeElem: function (elem) {
var parent = elem.parentNode;
if (parent && parent.nodeType !== 11) {
parent.removeChild(elem);
}
},
// url 組裝
parseData: function (data) {
var ret = "";
if (typeof data === "string") {
ret = data;
} else if (typeof data === "object") {
for (var key in data) {
ret += "&" + key + "=" + encodeURIComponent(data[key]);
}
}
// 加上時間戳防止快取
ret += "&_time=" + this.now();
return ret.substr(1);
},
getJSON: function (url, data, func) {
var name;
// 組裝 url
url = url + (url.indexOf("?") === -1 ? "?" : "&") + this.parseData(data);
// 檢查 callback 函式名是否已定義
var match = /callback=(\w+)/.exec(url);
if (match && match[1]) {
name = match[1];
} else {
// 未定義時隨機產生,時間戳加 16 位隨機數,重名機率近乎為零
// 例如 jsonp_1355750852040_8260732076596469
name = "jsonp_" + this.now() + '_' + this.rand();
url = url.replace("callback=?", "callback=" + name);
// 處理 ? 已被 encode 的情況
url = url.replace("callback=%3F", "callback=" + name);
}
// 建立 script 元素
var script = document.createElement("script");
script.type = "text/javascript";
script.src = url;
// 設定 id,方便後續刪除
script.id = "id_" + name;
// 把傳入的函式掛成全域函式供遠端呼叫
window[name] = function (json) {
window[name] = undefined; // 執行後銷毀
var elem = document.getElementById("id_" + name);
JSONP.removeElem(elem); // 清掉插入的 script,不污染 DOM
func(json);
};
// 插入到 head
var head = document.getElementsByTagName("head");
if (head && head[0]) head[0].appendChild(script);
}
};
呼叫方式與 jQuery 幾乎一致:
var data = { from: "北京", count: 27, output: "json", callback: "?" };
JSONP.getJSON("https://api.qunar.com/cdnWebservices.jcp", data, function (json) {
console.log(json);
});
// 也可以直接把參數拼在網址上
JSONP.getJSON("https://api.qunar.com/cdnWebservices.jcp?from=北京&count=27&output=json&callback=?",
null, function (json) { console.log(json); });
服務端實作非常簡單,以 PHP 為例:
$callback = !empty($_GET['callback']) ? $_GET['callback'] : 'callback';
echo $callback . '(' . json_encode($data) . ')';
1. 兩者在呼叫方式上「看起來」很像,都是請求一個 URL 再處理回傳資料,所以 jQuery、Ext 等框架都把 JSONP 當成 Ajax 的一種形式封裝。
2. 但本質不同:Ajax 的核心是透過 XMLHttpRequest 取得非本頁內容;JSONP 的核心是動態添加 <script> 標籤來呼叫伺服器提供的腳本。
3. 所以兩者的差別並不在「是否跨域」——Ajax 透過伺服器代理一樣能跨域,JSONP 也不排斥取得同域資料。
4. 另外,JSONP 只是一種做法或非強制性協議,它並不一定非用 JSON 格式傳資料,字串也行,只是這樣不利於提供公開服務。
總結一句:JSONP 不是 Ajax 的特例,即使 jQuery 把兩者封裝在一起,也改變不了這個事實。