如何设置$ .ajaxStart()和$ .ajaxStop()仅在POST请求时触发?

我想为ajax请求设置全局处理程序,但仅限于POST情况。

不幸的是,全局处理程序$.ajaxStart()$.ajaxStop()将触发所有请求,据我所知,没有参数传递给处理函数。 文档也很稀缺,因为大多数jQuery文档都是。

我可以在全局ajax处理程序中检测请求类型吗?

你必须使用这些事件: ajaxSend() ajaxComplete()

 $(document).ajaxSend(function (event, xhr, options) { if (options.type.toUpperCase() === "POST") console.log('POST request');; }).ajaxComplete(function (event, xhr, options) { if (options.type.toUpperCase() === "POST") console.log('POST request'); }); 

使用ajaxSend,您仍然可以使用以下xhr.abort()中止请求: xhr.abort()

编辑:

更好的方法是在@ DemoUser的答案中使用jQuery.ajaxPrefilter

我想你可以这样做:

 jQuery.ajaxPrefilter(function( options) { if(options.type !== 'POST') { options.global = false; } }); 

请参阅:: jQuery prefilters