微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

XMLHttpRequest() 以什么顺序执行

如何解决XMLHttpRequest() 以什么顺序执行

我想弄清楚如何使用普通的 javascript 切换样式显示

我有一个 XLMHttpRequest()。有用。 UI 显示是我正在处理的。我希望在将数据加载到数据库显示旋转图标。所以,我的代码打开了图标,但问题是当我添加

  document.getElementById('loading').style.display = "none";

将其重置为隐藏。它从不显示。所以,这是我的代码

    function runScript()
    {
        let xhr = new XMLHttpRequest();
        xhr.open('GET','wenoconnected.PHP',true);
        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        xhr.onprogress = function() {
           document.getElementById('loading').style.display = "block";
        }

        xhr.onreadystatechange = function () {
            if(this.readyState == 4 && this.status == 200) {
                console.log(this.responseText);
                if (this.responseText === 'imported') {
                        alert('Update Complete');
                    }
                 document.getElementById('loading').style.display = "none";
            }
        }
        xhr.send()
    }

我试图在显示警报后重新加载页面,但所做的只是在不执行 xhr.send() 的情况下立即重新加载页面。这就是为什么我想知道代码执行的顺序。这样我就知道把 display = "none" 放在哪里。

解决方法

延迟可能太低而无法注意到变化(可以通过在服务器上模拟高延迟来验证这一点)。尝试以下替代方法:

来自:

function runScript()
{
    let xhr = new XMLHttpRequest();
    xhr.open('GET','wenoconnected.php',true);
    xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    xhr.onprogress = function() {
       document.getElementById('loading').style.display = "block";
    }

    xhr.onreadystatechange = function () {
        if(this.readyState == 4 && this.status == 200) {
            console.log(this.responseText);
            if (this.responseText === 'imported') {
                    alert('Update Complete');
                }
             document.getElementById('loading').style.display = "none";
        }
    }
    xhr.send()
}

致:

function runScript()
{
    let xhr = new XMLHttpRequest();
    xhr.open('GET',"application/x-www-form-urlencoded");
    xhr.onreadystatechange = function () {
        if(this.readyState == 4 && this.status == 200) {
            console.log(this.responseText);
            if (this.responseText === 'imported') {
                    alert('Update Complete');
                }
             document.getElementById('loading').style.display = "none";
        }
    }

    document.getElementById('loading').style.display = "block";
    xhr.send()
}

假设:

  • GET 请求延迟足够慢,您会看到指示器
  • 没有其他与 CSS/HTML 相关的问题会阻止指示器显示
  • 无视显而易见的,比如;函数是否正在执行,是否有阻止相关代码执行的标识符的拼写错误等。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。