PHP下实现两种ajax跨域的解决方案之jsonp
?H5開發中使用ajax調用數據接口, 如果接口文件不在同域名下會提示跨域錯誤(No 'Access-Control-Allow-Origin' header is present on the requested resource.)。
1.兼容IE瀏覽器的方法,在Ajax請求的時候使用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("出現錯誤"+data.msg); } }, error : function(jqXHR) { alert("發生錯誤"+jqXHR.status); } }) });然后在PHP接收和返回的時候也帶上jsonp的數據:
function search() { $jsonp = $_GET["callback"];if(!isset($_GET["number"]) || empty($_GET["number"])) { echo '{"success":false,"msg":"參數錯誤"}'; return ; }global $staff;$number = $_GET["number"]; $result = $jsonp.'({"success":false,"msg":"沒有找到員工"})';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,而請求的域名是server.runoob.com。
如果直接使用ajax訪問,會有以下錯誤:
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、允許單個域名訪問
指定某域名(http://client.runoob.com)跨域訪問,則只需在http://server.runoob.com/server.php文件頭部添加如下代碼:
header('Access-Control-Allow-Origin:http://client.runoob.com');2、允許多個域名訪問
指定多個域名(http://client1.runoob.com、http://client2.runoob.com等)跨域訪問,則只需在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、允許所有域名訪問
允許所有域名訪問則只需在http://server.runoob.com/server.php文件頭部添加如下代碼:
//處理跨域
header("Access-Control-Allow-Origin:*"); //*號表示所有域名都可以訪問
header("Access-Control-Allow-Method:POST,GET");
?
轉載于:https://www.cnblogs.com/yuan9580/p/11343968.html
總結
以上是生活随笔為你收集整理的PHP下实现两种ajax跨域的解决方案之jsonp的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 纯css用图片代替checkbox和ra
- 下一篇: 使用 PHPMAILER 发送邮件实例