首页 热点资讯 义务教育 高等教育 出国留学 考研考公
您的当前位置:首页正文

Ajax跨域访问Cookie丢失问题的解决方法

来源:华拓网
Ajax跨域访问Cookie丢失问题的解决⽅法

ajax跨域访问,可以使⽤jsonp⽅法或设置Access-Control-Allow-Origin实现,关于设置Access-Control-Allow-Origin实现跨域访问可以参考之前我写的⽂章《》1.ajax跨域访问,cookie丢失⾸先创建两个测试域名

a.fdipzone.com 作为客户端域名b.fdipzone.com 作为服务端域名测试代码

setcookie.PHP ⽤于设置服务端cookie

setcookie('data', time(), time()+3600);>

server.php ⽤于被客户端请求

$name = isset($_POST['name'])? $_POST['name'] : '';$ret = array(

'success' => true, 'name' => $name,

'cookie' => isset($_COOKIE['data'])? $_COOKIE['data'] : '');

// 指定允许其他域名访问

header('Access-Control-Allow-Origin:http://a.fdipzone.com');// 响应类型

header('Access-Control-Allow-Methods:POST'); // 响应头设置

header('Access-Control-Allow-Headers:x-requested-with,content-type');header('content-type:application/json');echo json_encode($ret);>

test.html 客户端请求页⾯

ajax 跨域访问cookie丢失的解决⽅法

输出

{\"success\":true,\"name\":\"fdipzone\

获取cookie失败。2.解决⽅法客户端

请求时将withCredentials属性设置为true

使可以指定某个请求应该发送凭据。如果服务器接收带凭据的请求,会⽤下⾯的HTTP头部来响应。服务端设置header

header(\"Access-Control-Allow-Credentials:true\");

允许请求带有验证信息test.html 修改如下

ajax 跨域访问cookie丢失的解决⽅法

server.php 修改如下

$name = isset($_POST['name'])? $_POST['name'] : '';$ret = array(

'success' => true, 'name' => $name,

'cookie' => isset($_COOKIE['data'])? $_COOKIE['data'] : '');

// 指定允许其他域名访问

header('Access-Control-Allow-Origin:http://a.fdipzone.com');// 响应类型

header('Access-Control-Allow-Methods:POST'); // 响应头设置

header('Access-Control-Allow-Headers:x-requested-with,content-type');// 是否允许请求带有验证信息

header('Access-Control-Allow-Credentials:true');header('content-type:application/json');echo json_encode($ret);>

按之前步骤执⾏,请求返回

{\"success\":true,\"name\":\"fdipzone\

获取cookie成功3.注意事项

1.如果客户端设置了withCredentials属性设置为true,⽽服务端没有设置Access-Control-Allow-Credentials:true,请求时会返回错误。

XMLHttpRequest cannot load http://b.fdipzone.com/server.php. Credentials flag is 'true', but the 'Access-Control-Allow-Credentials' header is ''. It must be 'true' to allow credentials. Origin 'http://a.fdipzone.com' is therefore not allowed access.

2.服务端header设置Access-Control-Allow-Credentials:true后,Access-Control-Allow-Origin不可以设为*,必须设置为⼀个域名,否则回返回错误。

XMLHttpRequest cannot load http://b.fdipzone.com/server.php. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' heade

下⾯看下Ajax跨域请求COOKIE⽆法带上的解决办法原⽣ajax请求⽅式:

var xhr = new XMLHttpRequest();

xhr.open(\"POST\xhr.withCredentials = true; //⽀持跨域发送cookiesxhr.send();

jquery的ajax的post⽅法请求:

$.ajax({

type: \"POST\

url: \"http://xxx.com/api/test\ dataType: 'jsonp', xhrFields: {

withCredentials: true },

crossDomain: true, success:function(){ },

error:function(){ }})

服务器端设置:

header(\"Access-Control-Allow-Credentials: true\");

header(\"Access-Control-Allow-Origin: http://www.xxx.com\");

以上所述是⼩编给⼤家介绍的Ajax跨域访问Cookie丢失问题的解决⽅法,希望对⼤家有所帮助,如果⼤家有任何疑问请给我留⾔,⼩编会及时回复⼤家的。在此也⾮常感谢⼤家对⽹站的⽀持!

因篇幅问题不能全部显示,请点此查看更多更全内容