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");

 

---------------------
作者:_小小黑
来源:CSDN
原文:https://blog.csdn.net/u014520745/article/details/50777832?utm_source=copy
版权声明:本文为博主原创文章,转载请附上博文链接!

原文地址:https://www.cnblogs.com/zhang-bin/p/9789849.html