最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I set $.ajaxStart() and $.ajaxStop() to fire only on POST requests? - Stack Overflow

programmeradmin5浏览0评论

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?

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?

Share Improve this question asked Jun 7, 2013 at 9:35 GeorgeGeorge 4793 silver badges19 bronze badges 1
  • i don´t think so. although ajaxStop is called if EVERY ajax call has finished, therefore what should the request type be if there were more than one request. – luk2302 Commented Jun 7, 2013 at 9:42
Add a ment  | 

2 Answers 2

Reset to default 5

You have to use these events instead: 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');
});

Using ajaxSend, you can still abort request using: xhr.abort()

EDIT:

Better would be to use jQuery.ajaxPrefilter as in @DemoUser's answer

i guess you could do something like this:

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

See:: jQuery prefilters

发布评论

评论列表(0)

  1. 暂无评论