在上一篇文章中介紹了CORS跨源資源共享精偿,在本節(jié)中介紹JSONP跨源技術(shù)蜒谤。
JSONP也可以用來(lái)實(shí)現(xiàn)跨域資源請(qǐng)求棘劣,并且支持所有瀏覽器俏让,不過(guò)JSONP只支持GET請(qǐng)求。
JSONP不使用XMLHttpRequest 對(duì)象茬暇,而是用 script 標(biāo)簽首昔。
<script src="demo_jsonp.php">
** 完整示例:**
html代碼:
<!DOCTYPE html>
<html>
<body>
<button onclick="clickButton()">Click me!</button>
<p id="demo"></p>
<script>
function clickButton() {
var s = document.createElement("script");
s.src = "demo_jsonp.php";
document.body.appendChild(s);
}
function myFunc(myObj) {
document.getElementById("demo").innerHTML = myObj.name;
}
</script>
</body>
</html>
php代碼:
<?php
$myJSON = '{ "name":"John", "age":30, "city":"New York" }';
echo "myFunc(".$myJSON.");";
?>
返回一個(gè)以JSON數(shù)據(jù)為參數(shù)的名為myFunc函數(shù),并執(zhí)行糙俗。確崩掌妫客戶端中存在myFunc函數(shù)。
為了實(shí)現(xiàn)前后端分離臼节,在demo_jsonp.php后面添加查詢參數(shù)?callback=myFunc撬陵,現(xiàn)在的script的src為demo_jsonp.php?callback=myFunc,然后后端就可以根據(jù)查詢參數(shù)$_GET['callback']獲取回調(diào)函數(shù)名网缝。
jquery實(shí)現(xiàn)jsonp請(qǐng)求:
$.ajax("demo.php",{
dataType:"jsonp",
jsonp:"jsonpCallback", //此字段不指定的話默認(rèn)為callback,請(qǐng)求生成的url為demo_jsonp.php?jsonpCallback=myFunc
jsonpCallback:"myFunc", //此字段不指定的話默認(rèn)會(huì)生成一個(gè)隨機(jī)名稱蟋定,此例中不填會(huì)彈出error
success:function(){
alert("success")
},
error:function(){
alert("error")
}
})
ps:jsonp的jquery實(shí)現(xiàn)可以參考http://www.cnblogs.com/aaronjs/p/3785646.html