jQuery AJAX响应集Cookie标头 [英] jQuery AJAX Response Set Cookie Header

查看:215
本文介绍了jQuery AJAX响应集Cookie标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用REST API的项目.在这里,当发出登录请求时,他们会将包含一些数据的响应作为JSON发送给我.以及响应标题中的

I have a project which using a a REST API. Here when Isend a login request, they are sending me the response as JSON containg some data. Along with that in Response Header

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.

Here we have a Set-Cookie , but this cookie is not setting. I need this cookie to be setted, because for any other API access, the server will check for this cookie.

如何解决此问题? jQuery AJAX响应标头设置Cookie方法的解决方案是什么?

How can I resolve this Issue? What is the solution for jQuery AJAX response Header Set-Cookie method?

推荐答案

您可以从XMLHTTPRequest获取标头.这可能会有所帮助.让我知道这是否有效.

You can get headers from XMLHTTPRequest. This may help. Let me know if this is working.

$.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" : "" );
}

这篇关于jQuery AJAX响应集Cookie标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆