Wie kann die $.get()-Methode von Jquery beim Senden einer Anfrage Cookies mitbringen?
人生最曼妙的風(fēng)景,竟是內(nèi)心的淡定與從容!
首先,jquery的get方法和post方法都是對ajax的一種封裝,見源碼
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// Shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
// The url can be an options object (which then must have .url)
return jQuery.ajax( jQuery.extend( {
url: url,
type: method,
dataType: type,
data: data,
success: callback
}, jQuery.isPlainObject( url ) && url ) );
};
} );`
然后,發(fā)送請求的時(shí)候怎么才能帶上cookie?
ajax方法發(fā)送請求的時(shí)候,會自動帶上你所登錄的域名的cookie,不需要你設(shè)置。
所以,Jquery的$.get()方法什么時(shí)候都會帶上cookie
使用的時(shí)候客戶端會自動帶上cookie,jquery已經(jīng)封裝好了,如果你想自己自定義cookie的話,可以使用$.cookie插件去設(shè)置一下客戶端cookie最后get。
關(guān)于調(diào)試,你可以開啟控制臺F12,在network查看請求頭中的信息
先在控制臺Application
里面的cookies
選項(xiàng)里面找找,cookies
設(shè)置get
成功了沒。如果有設(shè)置好,客戶端在同一域名下,會自動在每個頁面帶上cookie
的。
發(fā)送請求時(shí)瀏覽器會自動攜帶cookie傳遞給后臺的,只有l(wèi)ocalStorage/sessionStorage的參數(shù)要傳遞的話需要異步時(shí)以參數(shù)傳遞
**$.support.cors = true;**
$.ajax({
url: urls.getDetailList,
type: "get",
dataType: "json",
**xhrFields: { withCredentials: true },**
success: function(res) {}
})
你應(yīng)該是$.support.cors跨域沒打開,加端代碼就可以 withCredentials,另外后端也要配跨域才行