【问题标题】:jQuery AJAX Response Set Cookie HeaderjQuery AJAX 响应集 Cookie 标头
【发布时间】:2012-10-09 17:38:44
【问题描述】:

我有一个使用 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响应Header Set-Cookie方法的解决方法是什么?

【问题讨论】:

  • 你在哪里提出这个请求?

标签: jquery cookies httpresponse jquery-cookie


【解决方案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" : "" );
}

【讨论】:

  • 此代码将为我的本地服务器设置 cookie。但我的问题是我需要为 API 服务器设置它。 Cookie 不提供任何域名。
  • 我还是不清楚..这段代码会在您的浏览器上设置来自您的 Web 服务器的 cookie
【解决方案2】:

我认为这里真正的问题是,如果您将浏览器的隐私/cookie 设置设置为偏执,那么某些浏览器(至少 FF 和 IE)似乎会忽略基于 XHR 的 Set-Cookie 标头。

这里是一些 FF 帮助的链接,可能对您的用户有用。 http://support.mozilla.org/en-US/kb/fix-login-issues-on-websites-require-passwords

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-06
    • 1970-01-01
    • 2014-03-30
    • 1970-01-01
    • 1970-01-01
    • 2016-05-22
    相关资源
    最近更新 更多