javascript - 第一个 AJAX 示例无法运行

标签 javascript html ajax

我已经开始学习 W3Schools 网站上的 AJAX 教程,但我的第一个示例甚至无法运行。请问这个为什么不运行?它在浏览器中打开,但当我单击按钮时没有任何反应。

教程网址;

https://www.w3schools.com/js/tryit.asp?filename=tryjs_ajax_ie

这是我在 Notepad++ 中创建的 HTML 页面

<!DOCTYPE html>
<html>
<body>

<h1>The XMLHttpRequest Object</h1>

<p id="demo">Let AJAX change this text.</p>

<button type="button" onClick="loadDoc()">Change Content</button>

<script>
  function loadDoc() {
  var xhttp;
  if (window.XMLHttpRequest) {
  // code for modern browsers
    xhttp = new XMLHttpRequest();
    } else {
    // code for IE6 and IE5
    xhttp = new ActiveXObject("Microsoft.XMLHTTP");
 }
  xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    document.getElementById("demo").innerHTML = this.responseText;
 }
};
 xhttp.open("GET", "ajax_info.txt", true);
 xhttp.send();
}
</script>
</body>
</html>

我通过在 Notepad++ 中选择“运行 >> chrome”来运行 HTML 页面(但也尝试了 Firefox 和 IE)。 ajax_info.txt 文件与 HTML 文件位于同一位置。这是其内容;

AJAX 不是一种编程语言。

AJAX 是一种从网页访问 Web 服务器的技术。

AJAX 代表异步 JavaScript 和 XML。

最佳答案

您必须更改 xhhtp.onreadystatechange 而不是 xhttp.onreadystatechangexhttp.send(); 而不是 xhttp.send ();

function loadDoc() {
    debugger;
  var xhhtp;
  if (window.XMLHttpRequest) {
  // code for modern browsers
    xhhtp = new XMLHttpRequest();
    } else {
    // code for IE6 and IE5
    xhhtp = new ActiveXObject("Microsoft.XMLHTTP");
 }
  xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    document.getElementById("demo").innerHTML = this.responseText;
 }
};
 xhhtp.open("GET", "ajax_info.txt", true);
 xhhtp.send();
}

关于javascript - 第一个 AJAX 示例无法运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43253495/

相关文章:

javascript - 使用 AngularJS 从 Iconic 框架的侧面菜单示例访问 'id' 值

javascript - 如果我在常规语法中包含 vendor 前缀,转换是否会应用两次?

javascript - Vue.js - 点击跨度也会点击输入。如何防止呢?

html - 目标元素不响应

html - CSS - 旋转边框 - 这可能吗?

javascript - 如何使用 link_to :remote => true 跟踪 ajax 调用

javascript - 翻转大部分 svg 图像,但不翻转其中的文本

javascript - 当我将 javascript 代码放入外部 Site.js 文件中时,Ajax pagemethod 不起作用

jquery - 将带有 JSON 数据的 fullcalendar 动态加载到 addEventSource 中

html - 使输入适合 td 的高度和宽度