jQuery中AJAX POST请求的全局事件处理程序

时间:2019-02-27 14:11:28

标签: jquery ajax

我想为jQuery.post(...)完成的所有POST请求注册一个事件处理程序。

我可以使用以下命令为所有ajax请求安装全局处理程序:

$( document ).ajaxComplete(function(ev,xhr) {
  console.log(xhr);
});

但是我想让处理程序仅用于POST请求。但我无法弄清楚:

$( document ).ajaxComplete(function(ev,xhr) {
  if(xhr.__IS_POST_OR_WHATEVER()) {
     console.log(xhr);
  }
});

1 个答案:

答案 0 :(得分:4)

还有一个附加参数传递给ajaxComplete事件处理程序;一个对象,其中包含发出请求的设置。该对象具有type属性,您需要检查该属性:

$(document).ajaxComplete(function(ev, xhr, settings) {
  if (settings.type === 'POST') {
    console.log('Do something');
  }
});

更多信息,请访问docs

相关问题