簡體   English   中英

如何使用 AJAX 請求設置 cookie 值?

[英]How to set cookie value with AJAX request?

我想在 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);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM