简体   繁体   中英

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

In my below code, I tried to stimulate how each statement gets executed line by line while processing synchronous ajax requests. I have sent two ajax requests synchronously introducing a delay between two requests. The problem is i'm getting "Request 1" in console but not getting the response text in my dom. After delay ends, and my second request ends, the first responseText is displayed and then second responseText is displayed in my dom.

Why My first ajax response text getting late to update in my dom, even though I got a response from server-side before the delay gets start?

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.

I think there is something wrong with your response. I used a publicly available fake endpoint to reproduce this, but it works as expected: https://jsbin.com/kojowaneda/1/edit?html,js,console,output

The only diff between this code and yours, is the parameter of the function call: <button type="button" onclick="loadDoc('https://jsonplaceholder.typicode.com/todos/1')">Synchronous Operations</button>

Also, you should use setTimeout for a timeout instead of a for loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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