我在同一个域上有一个 $.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,即使它们无法从 headers
或 document.cookie
中读取
关于jquery - 如何从 AJAX 响应中获取 cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12840410/