如何使用jQuery和Javascript禁用页面中的所有AJAX请求? [英] How to disable all AJAX requests in a page with jQuery and Javascript ?

查看:74
本文介绍了如何使用jQuery和Javascript禁用页面中的所有AJAX请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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
}


推荐答案

如果你的所有ajax请求都是通过jQuery ajax方法发送的(包括帮助方法) ),你可以用beforeSend做到这一点。

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.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虽然

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

这篇关于如何使用jQuery和Javascript禁用页面中的所有AJAX请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆