javascript 是否可以从 beforeSend 回调中修改 XMLHttpRequest 数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4527054/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to modify XMLHttpRequest data from beforeSend callback?
提问by veilig
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 回调中的 XMLHttpRequest 对象来修改 Ajax 请求中发送的数据?如果是这样,我该怎么做?
回答by Nick Craver
Yes you can modify it, the signature of beforeSendis actually(in jQuery 1.4+):
是的,你可以修改它的签名beforeSend是实际(jQuery中1.4+):
beforeSend(XMLHttpRequest, settings)
even though the documentation has just beforeSend(XMLHttpRequest), you can see how it's called here, where sis the settings object:
即使文档只有beforeSend(XMLHttpRequest),您也可以在这里看到它是如何调用的,s设置对象在哪里:
if ( s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false ) {
So, you canmodify the dataargument before then (note that it's alreadya string by this point, even if you passed in an object). An example of modifying it would look like this:
因此,您可以在此data之前修改参数(请注意,此时它已经是一个字符串,即使您传入了一个对象)。修改它的示例如下所示:
$.ajax({
//options...
beforeSend: function(xhr, s) {
s.data += "&newProp=newValue";
}
});
If it helps, the same signature applies to the .ajaxSend()global handler (which doeshave correct documentationshowing it), like this:
如果有帮助,相同的签名适用于.ajaxSend()全局处理程序(确实有正确的文档显示它),如下所示:
$(document).ajaxSend(function(xhr, s) {
s.data += "&newProp=newValue";
});
回答by talsibony
I was looking for this solution and wonder why I am not finding the s.data so I changed the request type to post and it was there, Looks like if you are using GET request the data property is not there, I guess you have to change the s.url
我一直在寻找这个解决方案,想知道为什么我没有找到 s.data 所以我将请求类型更改为 post 并且它在那里,看起来如果您使用 GET 请求数据属性不存在,我想您必须更改 s.url
for get method:
获取方法:
$.ajax({
type:'GET',
beforeSend: function(xhr, s) {
s.url += "&newProp=newValue";
}
});
for post method:
对于post方法:
$.ajax({
type:'POST',
beforeSend: function(xhr, s) {
s.data += "&newProp=newValue";
}
});

