6

I'd like to set global handlers for ajax requests, but only for POST cases.

Unfortunately, global handlers $.ajaxStart() and $.ajaxStop() will fire for all requests and as far as I can see there is no parameter passed onto the handler function. The documentation is also scarce, as most jQuery documentation is.

Can I detect the request type from within a global ajax handler?

4

2 回答 2

5

我想你可以做这样的事情:

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

请参阅:: jQuery 预过滤器

于 2013-06-07T09:51:06.450 回答
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');
});

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

编辑:

更好的是使用jQuery.ajaxPrefilter就像@DemoUser's answer

于 2013-06-07T09:55:24.830 回答