【问题标题】:How to print the response using AJAX/Javascript? [duplicate]如何使用 AJAX/Javascript 打印响应? [复制]
【发布时间】:2017-05-09 13:55:56
【问题描述】:

我正在了解AJAX,并试图让我的文件“info.txt”的内容显示在divid“演示”中。但是它一直返回空白。不幸的是,为了测试这一点,您必须在实际服务器(我就是)上尝试此代码,并且必须提供您自己的“info.txt”文件。请提供一个标准的javascript答案(非JQuery),拜托!

function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.open("GET", "info.txt", true);
  xhttp.send();
  document.getElementById("demo").innerHTML = xhttp.responseText;
}
<div id="demo">
<h1>The XMLHttpRequest Object</h1>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>

【问题讨论】:

标签: javascript ajax


【解决方案1】:

您传递给xhttp.opentrue 表示您的请求是异步的,这意味着它不会等待响应。

您需要删除 true(不推荐)或正确设置收到响应时的回调:

function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.open("GET", "info.txt", true);
  xhttp.onreadystatechange = function () {
    if (xhttp.readyState === XMLHttpRequest.DONE && xhttp.status === 200) {
      document.getElementById("demo").innerHTML = xhttp.responseText;
    }
  };
  xhttp.send();
}

【讨论】:

  • 啊...这就是我没有得到的。谢谢杰克。你能解释一下为什么send()onreadystatechange() 之后吗?
  • @GovindRai 因为您正在使用 onreadystatechange 定义一个回调,该回调在 发生任何更改时运行......或者在这种情况下,是否检查它是否完成(@ 987654328@)。考虑这一点的一种简单/简化的方法是,如果您要求某人为您去商店,然后对这些东西做点什么。你要告诉他们你想要什么 (open) 以及当他们回来 (onreadystatechange) 之前 你将他们发送到 (send) 他们去商店。
猜你喜欢
  • 1970-01-01
  • 2021-12-09
  • 1970-01-01
  • 2017-01-13
  • 1970-01-01
  • 2014-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多