站长资源
中国站长网站

ajax老是提示跨域,看看在php服务端的解决方法

在请求的页面头添加

// 指定允许其他域名访问
header('Access-Control-Allow-Origin: *');
// 响应类型
header('Access-Control-Allow-Methods: POST,GET');
// 响应头设置
header('Access-Control-Allow-Headers:x-requested-with,content-type');

这种方法在通用情况是好用的,但如果你是跨域请求一些带cookie,session就原地爆炸了~

会发现session和cookie在请求第一次就会消失了~

解决方法:

header('Access-Control-Allow-Origin: http://test.com');
header('Access-Control-Allow-Methods: POST,GET');
header("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Headers:x-requested-with,content-type');
    $.ajax({
        url:"http://xxxx.com",
        type:"get",
        dataType:"json",
        xhrFields:{withCredentials:true},
        success:function(res){
            
        }
    })

我们发现分别在php和前端增加了

//ajax
xhrFields:{withCredentials:true},
//php
Access-Control-Allow-Credentials: true

注意,在添加Credentials后,origin就不能使用通配符*了,必须指定域名!

本文出处:来自互联网信息共享,请勿相信收费信息站长资源 » ajax老是提示跨域,看看在php服务端的解决方法

评论 抢沙发

评论前必须登录!