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

How to disable all AJAX requests in a page with jQuery and Javascript ? - Stack Overflow

programmeradmin7浏览0评论

I have a page and I would like to disable all AJAX requests with jQuery.

Do you have any ideas? And if it is possible?

if (false) {
  //disable all ajax requests
}

I have a page and I would like to disable all AJAX requests with jQuery.

Do you have any ideas? And if it is possible?

if (false) {
  //disable all ajax requests
}
Share Improve this question edited May 23, 2014 at 14:37 Thibault 1,59616 silver badges22 bronze badges asked May 23, 2014 at 14:28 user3669206user3669206 731 silver badge3 bronze badges 4
  • Why would you want to do that? Do you have access to all the code? – cr0ss Commented May 23, 2014 at 14:30
  • Use a main var like disable_all_ajax and add a check in all ajax calls. if(disable_all_ajax === true){ alert('ITS DISABLED MUHAHA');} – Timmetje Commented May 23, 2014 at 14:32
  • setTimeout(function(){ callback();},9999999); ;P – nettux Commented May 23, 2014 at 14:34
  • The website is cached, so even if the server is down the pages are available to the user but the ajax requests will cause Network Error. Yes I have access to all the code. – user3669206 Commented May 23, 2014 at 14:35
Add a ment  | 

2 Answers 2

Reset to default 9

If all of your ajax requests are being sent through jQuery ajax methods (including helper methods), you can do this with beforeSend.

window.ajaxEnabled = true;
$.ajaxSetup({
    beforeSend: function(){ 
        return window.ajaxEnabled; 
    }
});

$.post("http://www.google."); // throws an error
window.ajaxEnabled = false;
$.post("http://www.google."); // doesn't throw an error

http://jsfiddle/k2T95/3


And here's one that will block all, regardless of what javascript library is sending it, also based on a global flag. Doesn't affect XDomainRequest obj though

(function (xhr) {
    var nativeSend = xhr.prototype.send;
    window.ajaxEnabled = true;

    xhr.prototype.send = function () {
        if (window.ajaxEnabled) {
             nativeSend.apply(this, arguments);   
        }
    };
}(window.XMLHttpRequest || window.ActiveXObject));

http://jsfiddle/k2T95/4/

EDIT: There are better ways, depending your specific case which i don't know

Try: {test it for cross browser support, i didn't do it}

XMLHttpRequest.prototype.send = function(){};

Not only for requests done in jQuery

If you want to re-enable it:

var oSend = XMLHttpRequest.prototype.send; // keep reference
XMLHttpRequest.prototype.send = function(){};

Then call:

XMLHttpRequest.prototype.send = oSend; // get back reference to prototype method
发布评论

评论列表(0)

  1. 暂无评论