jquery ajax.set,jQuery的AJAX响应集合cookie头(jQuery AJAX Response Set Co

在使用AARESTAPI的项目中,遇到登录请求返回的Set-Cookie头无法设置的问题。尽管响应包含Set-Cookie字段,但浏览器并未存储该cookie。解决方案可能涉及到从XMLHttpRequest获取响应头并手动设置cookie。文章提到了两种方法:一是通过jQuery的AJAX回调获取响应头中的Set-Cookie,并使用JavaScript设置cookie;二是检查浏览器的隐私/cookie设置,因为某些浏览器在隐私模式下可能忽略基于XHR的Set-Cookie头。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我有使用AA REST API的项目。 在这里,当Isend的登录请求,他们送我方含一些数据的响应作为JSON。 随着在响应头

Access-Control-Allow-Origin:*

Connection:keep-alive

Content-Length:239

Content-Type:application/json

Date:Fri, 19 Oct 2012 06:28:12 GMT

Server:Apache/2.2.22 (Amazon)

Set-Cookie:session=username; Path=/

在这里,我们有一个Set-Cookie ,但这个cookie不会设置。 我需要这个cookie被设置好的,因为任何其他的API访问,服务器将检查这个cookie。

我怎样才能解决这个问题? 什么是jQuery的AJAX响应头的Set-Cookie方法解决?

Answer 1:

您可以来自XMLHttpRequest的获得头。 这可能会有帮助。 让我知道这是工作。

$.ajax({

type: 'POST',

url:'url.do',

data: formData,

success: function(data, textStatus, XMLHttpRequest){

var cookietoSet=XMLHttpRequest.getResponseHeader('Set-Cookie');

Set_Cookie(cookietoSet.split('=')[0],cookietoSet.split('=')[1],expires, path, domain, secure)//change as per ur needs

}

error: function (XMLHttpRequest, textStatus, errorThrown) {

alert(XMLHttpRequest.getResponseHeader('some_header'));

}

});

function Set_Cookie( name, value, expires, path, domain, secure )

{

// set time, it's in milliseconds

var today = new Date();

today.setTime( today.getTime() );

/*

if the expires variable is set, make the correct

expires time, the current script below will set

it for x number of days, to make it for hours,

delete * 24, for minutes, delete * 60 * 24

*/

if ( expires )

{

expires = expires * 1000 * 60 * 60 * 24;

}

var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +

( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +

( ( path ) ? ";path=" + path : "" ) +

( ( domain ) ? ";domain=" + domain : "" ) +

( ( secure ) ? ";secure" : "" );

}

Answer 2:

我觉得这里真正的问题是,如果你有浏览器的隐私/ cookie设置设置为偏执然后一些浏览器(至少FF&IE)似乎忽略基于XHR的Set-Cookie头。

下面是一些FF的帮助,可能是为用户提供实用的链接。 http://support.mozilla.org/en-US/kb/fix-login-issues-on-websites-require-passwords

我希望有这8更好的答案/解决方法(

文章来源: jQuery AJAX Response Set Cookie Header

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值