前置知識點: 同源策略 & 跨域
什么是 JSONP?
JSONP(JSON with Padding)是資料格式JSON的一種“使用模式”,可以讓網(wǎng)頁從別的網(wǎng)域獲取資料。 —— 維基百科
JSONP 核心原理
-
script標簽不受同源策略影響。 - 動態(tài)插入到
DOM中的script腳本可以立即得到執(zhí)行。
實現(xiàn)步驟
- 客戶端創(chuàng)建一個
JavaScript函數(shù),用來接收服務(wù)端返回的數(shù)據(jù)。
function onResponse(data) {
// do something
}
- 客戶端動態(tài)插入
script標簽執(zhí)行請求。
var script = document.createElement('script')
script.src = 'protocal://domain:port/path?callback=onResponse'
document.head.appendChild(script)
document.head.removeChild(script)
- 服務(wù)端將數(shù)據(jù)和 js 回調(diào)函數(shù)名拼接為函數(shù)調(diào)用的字符串并返回給客戶端。
app.get('/path', function(request, response) {
var data = getData()
var callback = request.query.callback
var result = `${callback}(${JSON.stringify(data)});`
response.send(result)
})
- 客戶端接收到
script標簽響應(yīng)并自動執(zhí)行回調(diào)函數(shù)。
JSONP 的缺點
- 只能使用
GET請求。 - 動態(tài)插入的
script腳本可能被注入惡意代碼。