我想在 AJAX 请求上设置一个 cookie 值,但下面的代码不起作用。
$.ajax({
type: "GET",
url: "http://example.com",
cache: false,
setCookies: "lkfh89asdhjahska7al446dfg5kgfbfgdhfdbfgcvbcbc dfskljvdfhpl",
crossDomain: true,
dataType: 'json',
success: function (data) {
alert(data);
});
如何在 header 中设置 cookie?
最佳答案
基本上,ajax 请求和同步请求都会自动发送您的文档 cookie。因此,您需要将 cookie 设置为记录,而不是请求。但是,你的请求是跨域的,事情就变得复杂了。基于this answer ,另外要设置文档 cookie,你应该允许它发送到跨域环境:
type: "GET",
url: "http://example.com",
cache: false,
// NO setCookies option available, set cookie to document
//setCookies: "lkfh89asdhjahska7al446dfg5kgfbfgdhfdbfgcvbcbc dfskljvdfhpl",
crossDomain: true,
dataType: 'json',
xhrFields: {
withCredentials: true
},
success: function (data) {
alert(data);
});
关于javascript - 如何使用 AJAX 请求设置 cookie 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16851896/