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

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

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

如何在标题中设置cookie?

基本上,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); });