[英]How to set cookie in browser from ajax response
I have a javascript function using jQuery to make a POST request to a web service. 我有一个使用jQuery的javascript函数来向Web服务发出POST请求。 The web service response has a header "Set-Cookie: name=value; domain=api.mydomain.com; path=/", and a JSON body.
Web服务响应具有标头“ Set-Cookie:名称=值; domain = api.mydomain.com; path = /”和JSON正文。
I expected the browser to set the cookie, but it does not. 我希望浏览器设置cookie,但事实并非如此。 Am I mistaken about how this should work?
我是否误解了它应该如何工作? Is there another way to make the browser set the cookie returned in the response header?
还有另一种方法可以使浏览器设置响应头中返回的cookie吗?
$.ajax(
{
type: "POST",
url: "https://api.mydomain.com/service",
data: body,
success: handleSuccess,
error: handleFailure
}
);
You can use localStorage in jQuery to store the data in browser. 您可以在jQuery中使用localStorage在浏览器中存储数据。 To set the data use
设置数据使用
localStorage.youdataname = xyz;
To retrieve the data back just use 要取回数据,只需使用
alert(localStorage.yourdataname);
If the soul purpose of AJAX request is to set data in browser you can simply request the AJAX with above code. 如果AJAX请求的基本目的是在浏览器中设置数据,则只需使用上述代码即可请求AJAX。
According to the XMLHttpRequest Level 1 and XMLHttpRequest Level 2, this particular response headers falls under the "forbidden" response headers that you can obtain using getResponseHeader() 根据XMLHttpRequest级别1和XMLHttpRequest级别2,此特定响应标头属于“禁止”响应标头,您可以使用getResponseHeader()获得该响应标头。
$.ajax({
type: 'POST',
url:"https://api.mydomain.com/service",
data: body,
success: function(output, status, xhr) {
alert(xhr.getResponseHeader('Set-Cookie'));
},
cache: false
});
If it didn't work on your browser, then use this 如果您的浏览器无法正常运行,请使用此功能
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) != -1) return c.substring(name.length,c.length);
}
return "";
}
success: function(output, status, xhr) {
alert(getCookie("MyCookie"));
},
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.