简体   繁体   English

如何从 AJAX 响应中获取 cookie?

[英]How to get a cookie from an AJAX response?

I have a $.ajax request on the same domain and I want to read the cookie.我在同一个域上有一个$.ajax请求,我想读取 cookie。 It keeps returning null .它不断返回null

$.ajax({
    type: 'GET',
    url: myUrl,
    success: function(output, status, xhr) {
        alert(xhr.getResponseHeader("MyCookie"));
    },
    cache: false
});

Any ideas?有任何想法吗? I'm using Chrome for this.我正在为此使用 Chrome。

The browser cannot give access to 3rd party cookies like those received from ajax requests for security reasons, however it takes care of those automatically for you!出于安全原因,浏览器无法访问来自 ajax 请求的第三方 cookie,它会自动为您处理这些 cookie!

For this to work you need to:为此,您需要:

1) login with the ajax request from which you expect cookies to be returned: 1) 使用您希望从中返回 cookie 的 ajax 请求登录:

$.ajax("https://example.com/v2/login", {
     method: 'POST',
     data: {login_id: user, password: password},
     crossDomain: true,
     success: login_success,
     error: login_error
  });

2) Connect with xhrFields: { withCredentials: true } in the next ajax request(s) to use the credentials saved by the browser 2) 在下一个 ajax 请求中连接xhrFields: { withCredentials: true }以使用浏览器保存的凭据

$.ajax("https://example.com/v2/whatever", {
     method: 'GET',
     xhrFields: { withCredentials: true },
     crossDomain: true,
     success: whatever_success,
     error: whatever_error
  });

The browser takes care of these cookies for you even though they are not readable from the headers nor the document.cookie浏览器会为您处理这些 cookie,即使它们无法从headersdocument.cookie中读取

You're looking for a response header of Set-Cookie :您正在寻找Set-Cookie的响应标头:

xhr.getResponseHeader('Set-Cookie');

It won't work with HTTPOnly cookies though.但它不适用于 HTTPOnly cookie。

Update更新

According to the XMLHttpRequest Level 1 and XMLHttpRequest Level 2 , this particular response headers falls under the "forbidden" response headers that you can obtain using getResponseHeader() , so the only reason why this could work is basically a "naughty" browser.根据XMLHttpRequest Level 1XMLHttpRequest Level 2 ,这个特定的响应标头属于您可以使用getResponseHeader()获得的“禁止”响应标头,所以这可以工作的唯一原因基本上是一个“顽皮”的浏览器。

xhr.getResponseHeader('Set-Cookie');

It won't work for me.它对我不起作用。

I use this我用这个

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) != -1) return c.substring(name.length,c.length);
    }
    return "";
} 

success: function(output, status, xhr) {
    alert(getCookie("MyCookie"));
},

http://www.w3schools.com/js/js_cookies.asp http://www.w3schools.com/js/js_cookies.asp

Similar to yebmouxing I could not the类似于 yebmouxing 我不能

 xhr.getResponseHeader('Set-Cookie');

method to work.工作方法。 It would only return null even if I had set HTTPOnly to false on my server.即使我在服务器上将 HTTPOnly 设置为 false,它也只会返回 null。

I too wrote a simple js helper function to grab the cookies from the document.我也编写了一个简单的 js 辅助函数来从文档中获取 cookie。 This function is very basic and only works if you know the additional info (lifespan, domain, path, etc. etc.) to add yourself:此功能非常基本,只有在您知道要添加自己的附加信息(寿命、域、路径等)时才有效:

function getCookie(cookieName){
  var cookieArray = document.cookie.split(';');
  for(var i=0; i<cookieArray.length; i++){
    var cookie = cookieArray[i];
    while (cookie.charAt(0)==' '){
      cookie = cookie.substring(1);
    }
    cookieHalves = cookie.split('=');
    if(cookieHalves[0]== cookieName){
      return cookieHalves[1];
    }
  }
  return "";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM