php+ajax+jquery实现jsonp跨域
我們有這么個(gè)html文件test.html:
代碼如下:
?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
$.ajax({
type: "GET",
async: false,
url:"test.php",
dataType: "jsonp",
jsonp: "callback",//傳遞給請(qǐng)求處理程序或頁(yè)面的,用以獲得jsonp回調(diào)函數(shù)名的參數(shù)名(一般默認(rèn)為:callback)
jsonpCallback:"flightHandler",//自定義的jsonp回調(diào)函數(shù)名稱,默認(rèn)為jQuery自動(dòng)生成的隨機(jī)函數(shù)名,也可以寫"?",jQuery會(huì)自動(dòng)為你處理數(shù)據(jù)
success: function(json){
alert('您查詢到航班信息:票價(jià): ' + json.price + ' 元,余票: ' + json.tickets + ' 張?;卣{(diào)函數(shù)名為: '+json.func);
},
error: function(){
alert("fail");
}
});
});
</script>
</head>
<body>
</body>
</html>
?
然后,你可以再找個(gè)另外一個(gè)域名的web目錄,將文件test.php:
?
<?php
$callback = $_GET["callback"];
$a = array(
'code'=>'CA1998',
'price'=>'6000',
'tickets'=>20,
'func'=>$callback,
);
$result = json_encode($a);
echo "flightHandler($result)";
exit;
放到這個(gè)目錄下面去。這樣就可以測(cè)試了。
直接在瀏覽器訪問test.html.就可以看到效果了。
轉(zhuǎn)載于:https://www.cnblogs.com/matengfei123/p/6740880.html
總結(jié)
以上是生活随笔為你收集整理的php+ajax+jquery实现jsonp跨域的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: jmeter设置全局变量
- 下一篇: 关闭window端口445