javascript - 为什么 .innerHTML 在 xmlhttp.open() 和 .send() 之前更改?

标签 javascript ajax xmlhttprequest

我正在学习使用 xmlhttprequest/AJAX。在 w3schools 的示例代码中,我不明白为什么这一行:

document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

在此之前:

 xmlhttp.open("GET","demo_get.asp",true);
 xmlhttp.send();

按照我的想法,您应该在有任何responseText 可以执行任何操作之前发送 GET 请求。我的理解哪里有错误?

<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","demo_get.asp",true);
xmlhttp.send();
}
</script>
</head>
<body>

<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="myDiv"></div>

</body>
</html>

最佳答案

有问题的行位于 xmlhttp.onreadystatechange 内部,它是一个函数。注意它的使用方式:

xmlhttp.onreadystatechange = function ()
{
    ...
}

在本例中,它是一个回调函数 - 当 ajax 请求(又名 xmlhttp.send())完成时调用它。

在深入了解 ajax 之前,您可能需要温习一下 javascript。

关于javascript - 为什么 .innerHTML 在 xmlhttp.open() 和 .send() 之前更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10084703/

相关文章:

javascript - 如何在 mapDispatchToProps 中访问 mapStateToProps 添加的属性?

javascript - 将非 ui 逻辑放在 react/redux 应用程序中的什么位置?

javascript - Jquery 选择的插件样式在 Ajax 调用后丢失

javascript - POST 请求完成后的 GET 请求

node.js - 使用正则表达式检查相对 URL 是否有效?

javascript - 当特定的url加载时关闭android webview?

javascript - 如何使用 Javascript 添加 iPhone/iPad 检测?

c# - 根据 Checkbox 选中的数据做 Ajax 调用

java - 是否可以使用 HTTP POST 下载文件?

php - AJAX 功能在没有警报的情况下不起作用