最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to run a function when any XMLHttpRequest is complete? - Stack Overflow

programmeradmin2浏览0评论

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.

Is there any event that fires when any XMLHttpRequest is complete? (or any XMLHttpRequest state change?).

Unfortunately I cannot access the specific XMLHttpRequest object used to make the request.

Thanks,

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.

Is there any event that fires when any XMLHttpRequest is complete? (or any XMLHttpRequest state change?).

Unfortunately I cannot access the specific XMLHttpRequest object used to make the request.

Thanks,

Share Improve this question asked Aug 15, 2013 at 18:32 MCMMCM 4771 gold badge7 silver badges18 bronze badges 7
  • 4 If you're using jQuery exclusively for said ajax, yes. ajaxComplete. – Kevin B Commented Aug 15, 2013 at 18:34
  • @KevinB's suggestion would only work if the scripts that are not under your control rely on jQuery ajax. – Christophe Commented Aug 15, 2013 at 18:36
  • @Christophe That's what KevinB's comment says - If you're using jQuery exclusively for **said ajax**, – Ian Commented Aug 15, 2013 at 18:37
  • @Ian my point is that it's not just about what the OP is using, but also about what was used in the other scripts he didn't write. I doubt the other scripts rely on jQuery because the OP explicitly mentions the XMLHttpRequest object. – Christophe Commented Aug 15, 2013 at 18:41
  • 1 Do i really have to be that exact? i thought my comment covered both cases pretty well. said ajax, being ajax requests he wishes to know when they are done. – Kevin B Commented Aug 15, 2013 at 18:42
 |  Show 2 more comments

1 Answer 1

Reset to default 19

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)

  1. 暂无评论