jQuery 使用ajax beforeSend 修改数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3521594/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:35:41  来源:igfitidea点击:

using ajax beforeSend to modify data

jqueryajax

提问by devzero

Let's say I have an Ajax call from jQuery like this:

假设我有一个来自 jQuery 的 Ajax 调用,如下所示:

$.ajax({
   url: myUrl,
   data: myData,
   type:'post'
});

I would like to be able to add to the myData using

我希望能够使用添加到 myData

$.ajaxSetup({
   beforeSend: function(call){...}
});

The result should be that all ajax calls (both post and get) is modified so if i get an extra parameter IsAjax=true

结果应该是所有 ajax 调用(post 和 get)都被修改,所以如果我得到一个额外的参数 IsAjax=true

采纳答案by Mario

This blog postexplains how you can use $.ajaxSetupto add data. It accumulates like $.extendJust do this:

这篇博文解释了如何使用$.ajaxSetup添加数据。它像$.extend这样累积只需这样做:

$.ajaxSetup({
  data:{
    isAjax:true
  }
});

回答by verybadbug

$.ajaxSetup({
  beforeSend: function(jqXHR, settings) {
    settings.data = $.extend(settings.data, {isAjax: true});
    return true;
  }
});

回答by Jovanni G

You can just actually use beforeSend in $.ajax();

你可以在 $.ajax(); 中实际使用 beforeSend;

$.ajax({
  beforeSend: function(xhr){
    this.data += '&' + $.param({
      param: 'test'
    });
  }
});