問題描述
是否可以通過修改 beforeSend 回調中的 XMLHttpRequest 對象來修改 Ajax 請求中發送的數據?如果是這樣,我該怎么做?
Is it possible to modify the data sent in an Ajax request by modifying the XMLHttpRequest object in the beforeSend callback? and if so how might I do that?
推薦答案
可以修改,beforeSend
是 實際上 (在 jQuery 1.4+ 中):
Yes you can modify it, the signature of beforeSend
is actually (in jQuery 1.4+):
beforeSend(XMLHttpRequest, settings)
即使文檔只有 beforeSend(XMLHttpRequest)
,你可以在這里看到它是怎么調用的,這里s
是設置對象:
even though the documentation has just beforeSend(XMLHttpRequest)
, you can see how it's called here, where s
is the settings object:
if ( s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false ) {
因此,您可以在此之前修改 data
參數(請注意,此時它已經是一個字符串,即使你傳入了一個對象).修改它的示例如下所示:
So, you can modify the data
argument before then (note that it's already a string by this point, even if you passed in an object). An example of modifying it would look like this:
$.ajax({
//options...
beforeSend: function(xhr, s) {
s.data += "&newProp=newValue";
}
});
如果有幫助,同樣的簽名適用于 .ajaxSend()
全局處理程序(確實 有正確的 文檔 顯示它),例如這個:
If it helps, the same signature applies to the .ajaxSend()
global handler (which does have correct documentation showing it), like this:
$(document).ajaxSend(function(xhr, s) {
s.data += "&newProp=newValue";
});
這篇關于是否可以從 beforeSend 回調中修改 XMLHttpRequest 數據?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!