是否可以从beforeSend回调中修改XMLHttpRequest数据?
是否可以通过修改beforeSend回调中的XMLHttpRequest对象来修改Ajax请求中发送的数据? 如果是的话,我该怎么做?
是的你可以修改它,beforeSend的签名实际上是 (在jQuery 1.4+中):
beforeSend(XMLHttpRequest, settings)
即使文档只有beforeSend(XMLHttpRequest)
, 你也可以在这里看到它是如何被调用的 ,其中s
是设置对象 :
if ( s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false ) {
因此,您可以在此之前修改data
参数( 请注意 ,即使您传入了一个对象,此时它已经是一个字符串 )。 修改它的示例如下所示:
$.ajax({ //options... beforeSend: function(xhr, s) { s.data += "&newProp=newValue"; } });
如果它有帮助,相同的签名适用于.ajaxSend()
全局处理程序(它有正确的文档显示它),如下所示:
$(document).ajaxSend(function(xhr, s) { s.data += "&newProp=newValue"; });
我正在寻找这个解决方案并想知道为什么我找不到s.data所以我将请求类型更改为post并且它就在那里,看起来如果你使用GET请求数据属性不存在,我想你必须改变s.url
for get方法:
$.ajax({ type:'GET', beforeSend: function(xhr, s) { s.url += "&newProp=newValue"; } });
对于post方法:
$.ajax({ type:'POST', beforeSend: function(xhr, s) { s.data += "&newProp=newValue"; } });