How to run a function when any XMLHttpRequest is complete?

后端 未结 1 1321
星月不相逢
星月不相逢 2020-12-10 14:34

I\'m working on a project that has several scripts that I cannot change. These scripts update the page via AJAX. When the update is complete I need to run some code.

<
相关标签:
1条回答
  • 2020-12-10 15:18

    Without jQuery, you can hook the open method to attach a listener for each XHR object's readystatechange events at the time the XHR object is opened. Ensure the following code runs before any Ajax occurs:

    // save the real open
    var oldOpen = XMLHttpRequest.prototype.open;
    
    function onStateChange(event) {
        // fires on every readystatechange ever
        // use `this` to determine which XHR object fired the change event
    }
    
    XMLHttpRequest.prototype.open = function() {
        // when an XHR object is opened, add a listener for its readystatechange events
        this.addEventListener("readystatechange", onStateChange)
    
        // run the real `open`
        oldOpen.apply(this, arguments);
    }
    

    Alternatively, if you only care about successful load events, you can listener for that event instead of readystatechange.

    0 讨论(0)
提交回复
热议问题