PHP下实现两种ajax跨域的解决方案之jsonp
?H5開(kāi)發(fā)中使用ajax調(diào)用數(shù)據(jù)接口, 如果接口文件不在同域名下會(huì)提示跨域錯(cuò)誤(No 'Access-Control-Allow-Origin' header is present on the requested resource.)。
1.兼容IE瀏覽器的方法,在Ajax請(qǐng)求的時(shí)候使用jsonp:
$("#search").click(function() { $.ajax({ type : "GET", url : "http://127.0.0.1/raid/jquery_learning/ajax_learning/php/index.php?number="+$("#keyword").val(), dataType : "jsonp", jsonp : "callback", success : function(data) { if (data.success) { $("#searchResult").html(data.msg); } else { $("#searchResult").html("出現(xiàn)錯(cuò)誤"+data.msg); } }, error : function(jqXHR) { alert("發(fā)生錯(cuò)誤"+jqXHR.status); } }) });然后在PHP接收和返回的時(shí)候也帶上jsonp的數(shù)據(jù):
function search() { $jsonp = $_GET["callback"];if(!isset($_GET["number"]) || empty($_GET["number"])) { echo '{"success":false,"msg":"參數(shù)錯(cuò)誤"}'; return ; }global $staff;$number = $_GET["number"]; $result = $jsonp.'({"success":false,"msg":"沒(méi)有找到員工"})';foreach ($staff as $key => $value) { if($value["number"] == $number) { $result = $jsonp.'({"success":true,"msg":"找到員工'.$value["name"].'"})'; break; } }echo $result; }?
2.只提供給支持HTML5的瀏覽器使用,只需要在PHP的頭部加上如下這兩句話即可:
例如:客戶端的域名是client.runoob.com,而請(qǐng)求的域名是server.runoob.com。
如果直接使用ajax訪問(wèn),會(huì)有以下錯(cuò)誤:
XMLHttpRequest?cannot load http://server.runoob.com/server.php. No 'Access-Control-Allow-Origin' header is present on the requested resource.Origin 'http://client.runoob.com' is therefore not allowed access.
1、允許單個(gè)域名訪問(wèn)
指定某域名(http://client.runoob.com)跨域訪問(wèn),則只需在http://server.runoob.com/server.php文件頭部添加如下代碼:
header('Access-Control-Allow-Origin:http://client.runoob.com');2、允許多個(gè)域名訪問(wèn)
指定多個(gè)域名(http://client1.runoob.com、http://client2.runoob.com等)跨域訪問(wèn),則只需在http://server.runoob.com/server.php文件頭部添加如下代碼: $origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : ''; $allow_origin = array( 'http://client1.runoob.com', 'http://client2.runoob.com' ); if(in_array($origin, $allow_origin)){ header('Access-Control-Allow-Origin:'.$origin); }3、允許所有域名訪問(wèn)
允許所有域名訪問(wèn)則只需在http://server.runoob.com/server.php文件頭部添加如下代碼:
//處理跨域
header("Access-Control-Allow-Origin:*"); //*號(hào)表示所有域名都可以訪問(wèn)
header("Access-Control-Allow-Method:POST,GET");
?
轉(zhuǎn)載于:https://www.cnblogs.com/yuan9580/p/11343968.html
總結(jié)
以上是生活随笔為你收集整理的PHP下实现两种ajax跨域的解决方案之jsonp的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 纯css用图片代替checkbox和ra
- 下一篇: 微信小程序实现web端锚点功能