Is it possible to modify XMLHttpRequest data from beforeSend callback?

前端 未结 2 2031
走了就别回头了
走了就别回头了 2020-12-30 14:23

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?

2条回答
  •  不知归路
    2020-12-30 15:04

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

提交回复
热议问题