JSONP原理:
- 首先在客戶端注冊一個callback, 然后把callback的名字傳給服務器。
- 此時廊佩,服務器先生成 json 數(shù)據(jù)囚聚。
- 然后以 javascript 語法的方式,生成一個function , function 名字就是傳遞上來的callback參數(shù)值 .
- 最后將 json 數(shù)據(jù)直接以入?yún)⒌姆绞奖瓿胖玫?function 中顽铸,這樣就生成了一段 js 語法的文檔,返回給客戶端料皇。
- 客戶端瀏覽器谓松,解析script標簽,并執(zhí)行返回的 javascript 文檔践剂,此時數(shù)據(jù)作為參數(shù)鬼譬,傳入到了客戶端預先定義好的 callback 函數(shù)里.
jsonp 原理,代碼示意:
本地定義的函數(shù)===
<script>
function local_func(data) {
// 函數(shù)內(nèi)容
}
</script>
返回的數(shù)據(jù)放在srcipt標簽里===
<script src="http://api.douban.com/v2/movie/in_theaters?callback=local_func"></script>
等價于:
<script>
;local_func([返回的數(shù)據(jù)])
</script>
jsonp的2種實現(xiàn)方式:
- jsonp 在原生js中的實現(xiàn):
通過src="http://api.douban.com/v2/movie/in_theaters?callback=local_func"逊脯。
直接輸入訪問:http://api.douban.com/v2/movie/in_theaters 优质,返回的數(shù)據(jù)是一個對象:{xxx}。
直接輸入訪問:http://api.douban.com/v2/movie/in_theaters?callback=? 男窟,返回的數(shù)據(jù)是一個對象:{xxx}盆赤。
直接輸入訪問:http://api.douban.com/v2/movie/in_theaters?callback=local_func ,返回的數(shù)據(jù)是:;local_func({xxx})歉眷。
注意點:
callback指定的回調(diào)函數(shù)牺六,是客戶端注冊的,必須是定義在window下的全局函數(shù)汗捡。
例子網(wǎng)址:https://github.com/cag2050/jsonp_principle/blob/master/src/jsonp_js.html - jsonp 在jquery ajax中的實現(xiàn):
例子網(wǎng)址:https://github.com/cag2050/jsonp_principle/blob/master/src/jsonp_jquery.html
- 代碼所在github倉庫:https://github.com/cag2050/jsonp_principle