Is it possible to modify XMLHttpRequest data from beforeSend callback?

和自甴很熟 提交于 2019-12-18 12:38:52

问题


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?


回答1:


Yes you can modify it, the signature of beforeSend is actually (in jQuery 1.4+):

beforeSend(XMLHttpRequest, settings)

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 ) {

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";
  }
});

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";
});



回答2:


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

for get method:

$.ajax({
  type:'GET',
  beforeSend: function(xhr, s) {
    s.url += "&newProp=newValue";
  }
});

for post method:

$.ajax({
  type:'POST',
  beforeSend: function(xhr, s) {
    s.data += "&newProp=newValue";
  }
});


来源:https://stackoverflow.com/questions/4527054/is-it-possible-to-modify-xmlhttprequest-data-from-beforesend-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!