首页 > 解决方案 > 如何知道,AJAX 请求何时在 Native Javascript 中完全加载?

问题描述

这是我使用 setTimeout 进行的 AJAX 调用

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    document.getElementById('mainContent').style.display = 'none';
    if (this.readyState == 4 && this.status == 200) {
        xhttp.onload = function(){
            document.getElementById("mainContent").innerHTML = this.responseText;
            setTimeout(function(
               document.getElementById("mainContent").style.display = 'block';        
            ),1000);
        }
    }
};
xhttp.open("POST", "system.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("lang="+lang);    

我想检测ajax何时完全加载,我也有解决方案

我在这里有解决方案,但我不明白它是如何工作的。

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);
}

你能举例说明它是如何工作的或编写完整的代码它是如何工作的吗?

标签: javascript

解决方案


推荐阅读