前端Ajax,后端PHP
前端两个按钮
$("#sub").click(function(){
$.ajax({
type: "post",
url:"http://a.cn:81/index.php?act=1",
xhrFields: {
withCredentials: true//允许带上cookies
},
crossDomain: true,
data:$('#loginhttps://img-mid.csdnimg.cn/release/static/image/mid/ask/ed1b90bc5e844b98bb18bd82e76acdd7.png "#left")
Form').serialize(),
dataType: "json",//将返回数据数组化,否则返回的是字符串
success: function (result) {
console.log(result);
}
});
});
$("#sub2").click(function(){
$.ajax({
type: "post",
url:"http://a.cn:81/index.php?act=2",
xhrFields: {
withCredentials: true//允许带上cookies
},
crossDomain: true,
data:$('#loginForm').serialize(),
dataType: "json",//将返回数据数组化,否则返回的是字符串
success: function (result) {
console.log(result);
}
});
});
后端得设置header才能接收跨域信息
header("Access-Control-Allow-Credentials:true");
header("Access-Control-Allow-Origin:http://127.0.0.1");
// 设置一个存放目录,必须在 session_start() 函数调用之前调用
//$savePath = './session_save_dir/';
//session_save_path($savePath);//会导致获取不到session,后期想想怎么改吧
// 保存一天,必须在 session_start() 函数调用之前调用
$lifeTime = 24 * 60 * 60;
session_set_cookie_params($lifeTime);
session_start();
$act = $_REQUEST['act'];
if($act==1){
$userName = $_REQUEST['userName'];
$_SESSION["userName"] = $userName;//权限
setcookie(session_name(), session_id(), time() + $lifeTime, "/");
echo out_json(1, $_SESSION,$_COOKIE);exit;
}else{
echo out_json(2, $_SESSION,$_COOKIE);exit;
}
function out_json($code, $msg, $data)
{
$json['code'] = $code;
$json['msg'] = $msg;
$json['data'] = $data;
$json = json_encode($json);
return $json;
}
跨域的cookie获取不到,且再次访问session失效
请问这个要怎么解决