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

pow*_*ete 5 ajax jquery

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

我可以为所有ajax请求安装一个全局Handler:

$( document ).ajaxComplete(function(ev,xhr) {
  console.log(xhr);
});
Run Code Online (Sandbox Code Playgroud)

但我希望只为POST请求调用该处理程序.但我无法弄清楚:

$( document ).ajaxComplete(function(ev,xhr) {
  if(xhr.__IS_POST_OR_WHATEVER()) {
     console.log(xhr);
  }
});
Run Code Online (Sandbox Code Playgroud)

Ror*_*san 4

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

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

文档中提供了更多信息。