在下面的代码中,我试图激发每个语句在处理同步ajax请求时如何逐行执行。我已经发送了两个ajax请求,同时在两个请求之间引入了延迟。问题是我在控制台中收到“请求1”,但没有在我的dom中获得响应文本。延迟结束后,我的第二个请求结束,显示第一个responseText,然后在我的dom中显示第二个responseText。
为什么我的第一个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循环。