简体   繁体   中英

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. The web service response has a header "Set-Cookie: name=value; domain=api.mydomain.com; path=/", and a JSON body.

I expected the browser to set the cookie, but it does not. Am I mistaken about how this should work? Is there another way to make the browser set the cookie returned in the response header?

$.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. 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.

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()

$.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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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