jquery - 如何从 AJAX 响应中获取 cookie?

标签 jquery html ajax google-chrome

我在同一个域上有一个 $.ajax 请求,我想读取 cookie。它一直返回 null

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

有什么想法吗?为此,我正在使用 Chrome。

最佳答案

出于安全原因,浏览器无法访问第三方 cookie,例如从 ajax 请求收到的 cookie,但是它会自动为您处理这些!

为此,您需要:

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) 在下一个 ajax 请求中连接 xhrFields: { withCredentials: true } 以使用浏览器保存的凭据

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

浏览器会为您处理这些 cookie,即使它们无法从 headersdocument.cookie 中读取

关于jquery - 如何从 AJAX 响应中获取 cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12840410/

相关文章:

jquery - 检查 Capybara::Node::Element 是否已被 jQuery.remove() 删除

html - 下拉菜单不适用于导航菜单

css - 有人可以解释 CSS 和标记来制作类似 GMail 邮件 View 的表格吗?

html - 使用 2 个稍微旋转的 SVG 作为导航背景?

jquery - Ajax 添加 HTML 不继承页面样式 - jQuery Mobile

php - 将div中显示的值传递到php中的另一个页面

jquery - 如何使用 jQuery 或 mootools 触发 a 标签的 native (href)点击?

jquery - IE7 和 IE8 忽略带有 jQ​​uery 动态内容的 CSS

jquery - 从 jquery 表单中仅获取可见的单选按钮

php - MySQL 多重搜索与 jQuery/AJAX