简体   繁体   English

如何使用 AJAX 请求设置 cookie 值?

[英]How to set cookie value with AJAX request?

I want to set a cookie value on an AJAX request but the code below doesn't work.我想在 AJAX 请求上设置 cookie 值,但下面的代码不起作用。

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

How can I set cookies in the header?如何在标题中设置 cookie?

Basically, ajax request as well as synchronous request sends your document cookies automatically.基本上,ajax 请求以及同步请求会自动发送您的文档 cookie。 So, you need to set your cookie to document, not to request.因此,您需要将 cookie 设置为文档,而不是请求。 However, your request is cross-domain, and things became more complicated.但是,您的请求是跨域的,事情变得更加复杂。 Basing on this answer , additionally to set document cookie, you should allow its sending to cross-domain environment:基于这个答案,另外设置文档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);
});

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

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