繁体   English   中英

Dom 操作与 ajax 请求上的 javascript 代码不同步?

[英]Dom manipulations are not synchronized with javascript code on ajax request?

在我下面的代码中,我试图模拟在处理同步 ajax 请求时如何逐行执行每个语句。 我同步发送了两个 ajax 请求,在两个请求之间引入了延迟。 问题是我在控制台中收到“请求 1”,但在我的 dom 中没有收到响应文本。 延迟结束后,我的第二个请求结束,第一个 responseText 显示,然后第二个 responseText 显示在我的 dom 中。

为什么我的第一个 ajax 响应文本迟到在我的 dom 中更新,即使我在延迟开始之前收到了服务器端的响应?

index.html
-----------

<!DOCTYPE html>
<html>
<body>
    <!--Calls the function synchronously(async=0/false)  -->
    <button type="button" onclick="loadDoc('ajax_info.txt')">Synchronous Operations</button> 

    <p id="result1"></p>
    <p id="result2"></p>

</body>
<script type="text/javascript">
    function loadDoc(url) {

        console.log("Entered ");

        ajax(1,url,"result1");
        for(i=0;i<1000000000;i++){}
        ajax(2,url,"result2");

        console.log("Exit");
    }

    function ajax(requestNo, url, div) {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById(div).innerHTML = this.responseText;
                console.log("Request " + requestNo);
            }
        };
        xhttp.open("get", url, 0);
        xhttp.send();
    }
</script>
</html>

ajax_info.txt

--------------
This is the content from a txt file.

我认为你的回答有问题。 我使用了一个公开可用的假端点来重现这个,但它按预期工作: https : //jsbin.com/kojowaneda/1/edit? html,js,console, output

此代码与您的代码之间的唯一区别是函数调用的参数: <button type="button" onclick="loadDoc('https://jsonplaceholder.typicode.com/todos/1')">Synchronous Operations</button>

此外,您应该将 setTimeout 用于超时而不是 for 循环。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM