我需要为HTTP请求设置cookie。
可以这样做吗?
$.ajax({
method: "POST",
url: "http://example.org/",
dataType: "html",
data: {
game: "soccer",
value: "2395",
action: "newGame"
},
cookies: {
"domain": ".example.org",
"name": "SESSION",
"path": "/",
"value": "34645645765756757"
}
}).done(function( msg ) {
console.log(msg);
});
您无需在请求中明确添加cookie,它将发送您当前拥有的cookie。
如果您尝试链接到其他网站,则需要设置HTTP跨域访问:https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
并使用
$.ajax({
url: a_cross_domain_url,
xhrFields: {
withCredentials: true
}
});
您也可以尝试在请求之前重置Cookie标头
$.ajax({
//...
beforeSend: function(request) {
request.setRequestHeader("Cookie", "name=value; name2=value2; name3=value3");
},
//...
});
将自动发送和接收所有相同域请求的Cookie。
如果您需要发送和接收跨域cookie设置withCredentials
。你无法控制这些cookie是什么
$.ajax({
url: a_cross_domain_url,
xhrFields: {
withCredentials: true
}
//... other options
});