JSONP是為解決跨域而生麸粮,說(shuō)起跨域先理解一下同源溉苛,只有當(dāng)域名、端口弄诲、協(xié)議一樣的情況下才是同源愚战,其他的都是不同源,當(dāng)不同源發(fā)出的ajax請(qǐng)求就是跨域齐遵,這個(gè)時(shí)候會(huì)被瀏覽器攔截寂玲。
JSONP 是 JSON with padding(填充式 JSON 或參數(shù)式 JSON)的簡(jiǎn)寫(xiě)。JSONP實(shí)現(xiàn)跨域請(qǐng)求的原理簡(jiǎn)單的說(shuō)梗摇,就是動(dòng)態(tài)創(chuàng)建<script>標(biāo)簽拓哟,然后利用<script>的src 不受同源策略約束來(lái)跨域獲取數(shù)據(jù)。
JSONP 由兩部分組成:回調(diào)函數(shù)和數(shù)據(jù)伶授《闲颍回調(diào)函數(shù)是當(dāng)響應(yīng)到來(lái)時(shí)應(yīng)該在頁(yè)面中調(diào)用的函數(shù)流纹。回調(diào)函數(shù)的名字一般是在請(qǐng)求中指定的违诗。而數(shù)據(jù)就是傳入回調(diào)函數(shù)中的 JSON 數(shù)據(jù)漱凝。
后端服務(wù)
@RequestMapping(value = "jsonp",method = RequestMethod.GET)
@ResponseBody
public Object jsonp(@RequestParam(value = "callback",required = false) String callback){
Map<String,Object> map= new HashMap<>();
map.put("a",123);
map.put("b","234");
if(StringUtils.isEmpty(callback)){
return map;
}
return callback+"("+ JSON.toJSONString(map)+")";
}
- jQuery封裝JSONP
$.getJSON(
"http://localhost:9999/aop/jsonp?callback=?",
function(data){
console.log(data);
});
或者:
$.ajax({
type: "GET",
url: "http://localhost:9999/aop/jsonp",
dataType: "jsonp",
headers: {
"Accept" : "application/json; charset=utf-8",
"Content-Type": "application/javascript; charset=utf-8",
"Access-Control-Allow-Origin" : "*"
},
success: function (result) {
console.log(result);
},
error: function (xhr, errorText) {debugger;
console.log('Error ' + xhr.responseText);
}
});
- 動(dòng)態(tài)創(chuàng)建script標(biāo)簽
function handleResponse(data){
console.log(data);
}
var script = document.createElement("script");
script.src = "http://localhost:9999/aop/jsonp?callback=handleResponse";
document.body.insertBefore(script, document.body.firstChild);