如何使用jQuery和Javascript禁用页面中的所有AJAX请求?

我有一个页面,我想用jQuery禁用所有AJAX请求。

你有什么想法? 如果可能的话?

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

如果所有的ajax请求都是通过jQuery ajax方法(包括帮助方法)发送的,那么你可以使用beforeSend来完成。

 window.ajaxEnabled = true; $.ajaxSetup({ beforeSend: function(){ return window.ajaxEnabled; } }); $.post("http://www.google.com"); // throws an error window.ajaxEnabled = false; $.post("http://www.google.com"); // doesn't throw an error 

http://jsfiddle.net/k2T95/3


这里有一个将阻止所有,无论javascript库发送它,也基于全局标志。 但是不影响XDomainRequest obj

 (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.net/k2T95/4/

编辑:有更好的方法,根据您不知道的具体情况

尝试:{测试它是否支持跨浏览器支持,我没有这样做}

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

不仅适用于jQuery中的请求

如果要重新启用它:

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

然后打电话:

 XMLHttpRequest.prototype.send = oSend; // get back reference to prototype method