在做一个跨域请求的功能时需要用到cookie,但是正常的跨域浏览器不允许跨域请求带上cookie和获取cookie的,所以需要在代码上做一些修改。
前端AJAX:
$.ajax({
type: "POST",
url: "getlistener.php",
dataType: 'json',
xhrFields: {withCredentials: true},//设置withCredentials为TRUE,为TRUE而执行跨域名请求
data:{business_id:1},
success:function(data){
},
error:function(){}
});
后端执行方法:
function getlistener(){
$domian = $_SERVER['HTTP_ORIGIN'];//获取请求的域名
header('Access-Control-Allow-Origin:'.$domian); //允许的域名,可以设置指定域名
header('Access-Control-Allow-Credentials:true');//是否允许请求带有验证信息
//处理逻辑写在这里
return json_encode($data);
}