PHP与Ajax 跨域问题最佳解决方案

例如:客户端的域名是client.hengboit.com,而请求的域名是www.hengboit.com。
如果直接使用ajax访问,会有以下错误:

XMLHttpRequest cannot load http://www.hengboit.com/server.php. No 'Access-Control-Allow-Origin' header is present on the

requested resource.Origin 'http://client.hengboit.com' is therefore not allowed access.

1、允许单个域名访问

指定某域名(http://client.hengboit.com)跨域访问,只需在http://www.hengboit.com/server.php文件头部添加如下代码:

header('Access-Control-Allow-Origin:http://client.hengboit.com');

2、允许多个域名访问:

指定多个域名(http://client1.hengboit.com、http://client2.hengboit.com等)跨域访问,则只需在

http://www.hengboit.com/server.php文件头部添加如下代码:

$origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : '';

$allow_origin = array(
'http://client1.hengboit.com',
'http://client2.hengboit.com'
);

if(in_array($origin, $allow_origin)){
header('Access-Control-Allow-Origin:'.$origin);

3、允许所有域名访问

允许所有域名访问则只需在http://www.hengboit.com/server.php文件头部添加如下代码:

header('Access-Control-Allow-Origin:*')

Mui异步获取 服务器头部声明
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST");
header("Access-Control-Allow-Headers: Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With");

 

 

html
<script type="text/javascript" src="http://www.bjyasina.com/Public/home/js/jquery.min.js"></script>
<script>
$.ajax({
type: "GET",
url:"http://127.0.0.10/YaSiNaAdmin/Index/nav",
success: function(data){
console.log(data);
}
})
</script>

MUI

mui.ajax('http://127.0.0.10/YaSiNaAdmin/Index/nav',{
success:function(data){

console.log(data);
},
});


posted on 2017-02-15 15:36  炊厨  阅读(177)  评论(0)    收藏  举报

导航