How to set cookie value with AJAX request?

前端 未结 1 1712
情歌与酒
情歌与酒 2020-12-13 17:54

I want to set a cookie value on an AJAX request but the code below doesn\'t work.

$.ajax({
    type: \"GET\",    
    url: \"http://example.com\",
    cache         


        
相关标签:
1条回答
  • 2020-12-13 18:26

    Basically, ajax request as well as synchronous request sends your document cookies automatically. So, you need to set your cookie to document, not to request. However, your request is cross-domain, and things became more complicated. Basing on this answer, additionally to set document cookie, you should allow its sending to cross-domain environment:

    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);
    });
    
    0 讨论(0)
提交回复
热议问题