JQuery 可以侦听来自其他 javascript 的 AJAX 调用吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/4406606/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can JQuery listen to AJAX calls from other javascript?
提问by BudgieInWA
I need to build a feature into a shopping cart that uses AJAX to retrieve an updated copy of the template from the server when something changes (e.g. a product is removed). I cannot modify the server side code, or the JavaScript that makes the shopping cart work in the first place. (Not ideal I know, but that's how it is)
我需要在购物车中构建一个功能,当某些内容发生变化(例如,产品被删除)时,该功能使用 AJAX 从服务器检索模板的更新副本。我无法修改服务器端代码,或者首先使购物车工作的 JavaScript。(我知道不理想,但事实就是这样)
What I want to do is run my own JavaScript every time the cart updates. I want to know if it is possible to listen for AJAX calls, and run my code every time one is made.
我想做的是每次购物车更新时运行我自己的 JavaScript。我想知道是否可以监听 AJAX 调用,并在每次调用时运行我的代码。
回答by Nicolas
To follow all AJAX calls on an HTML doc, you can overwrite the XMLHttpRequestprototype.
This way, you can watch for actions on methods of XMLHttpRequestobjects.
要跟踪 HTML 文档上的所有 AJAX 调用,您可以覆盖XMLHttpRequest原型。通过这种方式,您可以观察XMLHttpRequest对象方法上的操作。
Here's a small sample code :
这是一个小示例代码:
var open = window.XMLHttpRequest.prototype.open,
    send = window.XMLHttpRequest.prototype.send,
    onReadyStateChange;
function openReplacement(method, url, async, user, password) {
    var syncMode = async !== false ? 'async' : 'sync';
    console.warn(
        'Preparing ' +
        syncMode +
        ' HTTP request : ' +
        method +
        ' ' +
        url
    );
    return open.apply(this, arguments);
}
function sendReplacement(data) {
    console.warn('Sending HTTP request data : ', data);
    if(this.onreadystatechange) {
        this._onreadystatechange = this.onreadystatechange;
    }
    this.onreadystatechange = onReadyStateChangeReplacement;
    return send.apply(this, arguments);
}
function onReadyStateChangeReplacement() {
    console.warn('HTTP request ready state changed : ' + this.readyState);
    if(this._onreadystatechange) {
        return this._onreadystatechange.apply(this, arguments);
    }
}
window.XMLHttpRequest.prototype.open = openReplacement;
window.XMLHttpRequest.prototype.send = sendReplacement;
With this sample, for every AJAX call you'll have a warning in the JavaScript console.
对于此示例,对于每个 AJAX 调用,您都会在 JavaScript 控制台中收到警告。
It's not jQuery script, but you can use jQuery inside as you want.
它不是 jQuery 脚本,但您可以根据需要在内部使用 jQuery。
This solution probably won't work on IE 6 or older, but it works in FF, IE7+, Chrome, Opera, Safari...
此解决方案可能不适用于 IE 6 或更早版本,但适用于 FF、IE7+、Chrome、Opera、Safari...
回答by Yuriy Yakubskiy
I'd prefer this solution.
我更喜欢这个解决方案。
$(document).ajaxComplete(function(event,request, settings){
    // Your code here
});
回答by Ravinder Payal
My Friend You can do this very easily with Jquery (As You have told You Are using Jquery)
我的朋友你可以用 Jquery 很容易地做到这一点(正如你所说的你正在使用 Jquery)
(For those who are not using they can drive in Jquery library code under ajax function to view native code :') )
(不使用的可以在ajax函数下驱动Jquery库代码查看本机代码:'))
$(document).bind("ajaxSend", function(){
   $("#loading").show();
 }).bind("ajaxComplete", function(){
   $("#loading").hide();
 });
This is an code snippet taken from jquery official api docs ( See Global Events Section)
这是取自 jquery 官方 api 文档的代码片段(请参阅全局事件部分)
回答by Jinesh Parekh
You cannot listen to it but you can use a periodic updater plugin. Look at the below:
您无法收听它,但您可以使用定期更新程序插件。看看下面的:
http://plugins.jquery.com/plugin-tags/periodic-updater
回答by Adelmar
This takes the same approach of adding a callback in the XHR prototype, but without setting any new properties on the prototype or writing our own event chaining mechanism. I think this is less likely to introduce conflicts.
这与在 XHR 原型中添加回调的方法相同,但没有在原型上设置任何新属性或编写我们自己的事件链机制。我认为这不太可能引起冲突。
(function() {
  // Reference to the original prototype method we're overriding
  var originalOpen = XMLHttpRequest.prototype.open;
  // Override prototype.open to add a custom callback whenever a request is opened
  XMLHttpRequest.prototype.open = function() {
    this.addEventListener('loadend', customCallback);
    // Execute the original prototype.open without affecting its execution context
    originalOpen.apply(this, arguments);
  };
  // All instances of XMLHttpRequest will execute this callback once on readyState 4
  var customCallback = function () {
    // In this context, `this` refers to the XHR instance that just completed
    console.log(this);
    // Remove the invoking listener to prevent duping on multiple calls to .open
    this.removeEventListener('loadend', customCallback);
  }
}());
This won't work in IE <= 8 (no support for .addEventListener())
这在 IE <= 8 中不起作用(不支持.addEventListener())

