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

Geo*_*rge 5 javascript ajax jquery

我想为ajax请求设置全局处理程序,但仅限于POST案例.

不幸的是,全球处理器$.ajaxStart()$.ajaxStop()必火的所有请求,并尽可能我可以看有没有传递到处理函数的参数.文档也很稀缺,因为大多数jQuery文档都是.

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

Sud*_*oti 5

我想你可以这样做:

jQuery.ajaxPrefilter(function( options) {
    if(options.type !== 'POST') {
        options.global = false;
    }
});
Run Code Online (Sandbox Code Playgroud)

请参阅:: jQuery prefilters


A. *_*lff 5

你必须使用这些事件: 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');
});
Run Code Online (Sandbox Code Playgroud)

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

编辑:

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