我的JavaScript代码的问题在哪里

Where is the issue with my javascript code?

本文关键字:问题 在哪里 代码 JavaScript 我的      更新时间:2023-09-26

好的,所以我正在尝试使用javascript HTTPRequest来加载一个名为"chem_vocab.xml"的XML文档。但是,每当我尝试执行该功能时,都不会发生任何事情。我放置了几行 alert(),这样我可以看到我的故障发生在哪里。似乎在以下两者之间存在一些问题:

alert("Beginning Loading");

alert("XML Loaded");

页面将正确提醒"正在开始加载...",但不会提醒"XML 已加载"。我的问题在哪里?

function load_vocab(){
alert("Beginning Loading...");
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","chem_vocab.xml",true);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML; 
alert("XML loaded");
var x=xmlDoc.getElementsByTagName("wordlist")[0];
x= x.getElementsByTagName("word")[0];
word = x.getElementsByTagName("spelling")[0].childNodes[0].nodeValue;
definition = x.getElementsByTagName("definition")[0].childNodes[0].nodeValue;
alert("XML parsing successful");
document.getElementById('spelling').innerHTML = word;
document.getElementById('definition').innerHTML = definition;

}

您的代码:

xmlhttp.open("GET","chem_vocab.xml",true);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML; 

您的 Ajax 请求是异步的。因此,您不能在发送后立即读取 .responseXML 属性。xmlDoc的值将为空/未定义。您必须从readystatechange回调中执行此操作。

由于您似乎缺乏使用 Ajax 的经验,请考虑使用第三方 Ajax 库(例如 jQuery,如果您不使用通用库,则使用 miniajax)。

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
      xmlDoc=xmlhttp.responseXML; 
      alert("XML loaded");
      var x=xmlDoc.getElementsByTagName("wordlist")[0];
      x= x.getElementsByTagName("word")[0];
      word = x.getElementsByTagName("spelling")[0].childNodes[0].nodeValue;
      definition = x.getElementsByTagName("definition")[0].childNodes[0].nodeValue;
      alert("XML parsing successful");
      document.getElementById('spelling').innerHTML = word;
      document.getElementById('definition').innerHTML = definition;
    }
  }

您的代码是异步的。您必须先等待响应,然后才能执行xmlDoc=xmlhttp.responseXML;。因此,您需要为 onreadystatechange 事件添加一个事件处理程序,以便您获得响应。这就是上面的代码所做的

异步调用并期望它同步返回。使用此代码使调用不受阻塞,因此永远不会加载响应。

xmlhttp.open("GET","chem_vocab.xml",true); // True means non-blocking, you need a listener

因此,这将始终为空。

xmlDoc=xmlhttp.responseXML; 

根据此文档快速而肮脏的修复。

xmlhttp.open('GET', 'chem_vocab.xml', false);
xmlhttp.send(); // because of "false" above, will block until the request is done 
                // and status is available. Not recommended, however it works for simple cases.
if (xmlhttp.status === 200) {
  console.log(request.responseText);
  xmlDoc=xmlhttp.responseXML;
}