jQuery AJAX响应设置Cookie头部

5

我有一个使用REST API的项目。在发送登录请求时,他们会将响应以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方法的解决方案是什么?


你在哪里发起这个请求? - Jan Hančič
2个回答

6
您可以通过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没有提供任何域名。 - Jubin Thomas
我还不太清楚...这段代码将在您的浏览器上设置来自您的 Web 服务器的 cookie。 - thecodejack

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接