3
如何在jQuery .load()函數中傳遞Accept標頭,因爲它需要傳遞。如何在jQuery .load()函數中傳遞Accept標頭
如何在jQuery .load()函數中傳遞Accept標頭,因爲它需要傳遞。如何在jQuery .load()函數中傳遞Accept標頭
如在earlier answer by Jon提到,load
本身不能做到這一點。我更喜歡使用headers
選項上ajax
方法,而不是beforeSend
:
$.ajax({
url: "http//example.com",
headers: {
Accept: "application/whatever" // Use the actual type you need.
},
success: function (data) {
// Put the data into the element you care about.
$("#foo").html(data);
},
error: function (jqXHR) {
// Put whatever you need to do if the query fails here.
}
});
最終的結果是一樣的,但如果我喜歡節約的按鍵。
你需要利用在ajax
方法beforeSend
參數,因爲load
不公開此功能:
$.ajax({
url: "http://www.server.com/",
beforeSend: function(jqXHR, settings) {
jqXHR.setRequestHeader("Accept", "application/json");
},
// You need to manually do the equivalent of "load" here
success: function(result) {
$("selector").html(result);
}
});
好的,如果我想用head,body等替換所有的html,我應該使用哪個選擇器? – rcanovas
@rcanovas我不知道是否有適當的選擇器爲jQuery來做到這一點,但你可以使用普通的JS:'document.documentElement.innerHTML = data' – Louis