是否可以从 beforeSend 回调中修改 XMLHttpRequest 数据?
是否可以通过修改 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";
});
相关文章