41

我想在 AJAX 请求上设置一个 cookie 值,但下面的代码不起作用。

$.ajax({
    type: "GET",    
    url: "http://example.com",
    cache: false,
    setCookies: "lkfh89asdhjahska7al446dfg5kgfbfgdhfdbfgcvbcbc dfskljvdfhpl",
    crossDomain: true,
    dataType: 'json',
    success: function (data) {
        alert(data);
    });

如何在标题中设置 cookie?

4

1 回答 1

50

基本上,ajax 请求以及同步请求会自动发送您的文档 cookie。因此,您需要将 cookie 设置为文档,而不是请求。但是,您的请求是跨域的,事情变得更加复杂。基于这个答案,除了设置文档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);
});
于 2013-05-31T07:38:14.417 回答