可以JQuery的听取其他JavaScript AJAX调用? [英] Can JQuery listen to AJAX calls from other javascript?

查看:79
本文介绍了可以JQuery的听取其他JavaScript AJAX调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要建立一个功能到使用AJAX来从服务器获取模板的更新的副本,当有新的变化的购物车(例如,产品被删除)。我不能修改服务器端code,或使摆在首位购物车工作的JavaScript。 (不理想,我知道,但是这是怎么回事)

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)

我想要做的就是经营自己的JavaScript每次车更新什么。 我想知道是否可以侦听AJAX调用,然后运行我的code的每一个由时间。

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.

推荐答案

这是一个老问题,但也许这个答案可以帮助别人。

It's an old question, but maybe this answer can help others.

要遵循一个HTML文档的所有Ajax调用,您可以覆盖XMLHtt prequest原型。 这样,您就可以观看上XMLHtt prequest对象的方法操作。

To follow all ajax calls on an HTML doc, you can overwrite the XMLHttpRequest prototype. This way, you can watch for actions on methods of XMLHttpRequest objects.

下面是一个小样本code:

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;

通过这个例子中,对于每一个AJAX调用你必须在JavaScript控制台的警告。

With this sample, for every AJAX call you'll have a warning in the javascript console.

这不是jQuery脚本,但你可以使用jQuery只要你想进去。

It's not jQuery script, but you can use jQuery inside as you want.

此解决方案可能不会对IE 6或以上的工作,但它工作在FF,IE7 +,Chrome浏览器,歌剧,Safari浏览器...

This solution probably won't work on IE 6 or older, but it works in FF, IE7+, Chrome, Opera, Safari...

这篇关于可以JQuery的听取其他JavaScript AJAX调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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