如何使用AJAX请求设置cookie值

How to set cookie value with AJAX request?

本文关键字:cookie 设置 请求 何使用 AJAX      更新时间:2023-09-26

我想在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设置为document,而不是request。但是,您的请求是跨域的,事情变得更加复杂。基于这个答案,除了设置文档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);
});