我目前正在使用 JavaScript 编写搜索功能。
但是,当我尝试测试我的创作时,我发现它会莫名其妙地中途停止。
下面是我的代码:
document.getElementById("test").innerHTML = "";
var Connect = new XMLHttpRequest();
Connect.open("GET", "xmlTest.xml", false);
document.getElementById("test").innerHTML = "1";
Connect.send(null);
document.getElementById("test").innerHTML = "2";
var docX = Connect.responseXML;
var linjer = docX.getElementsByTagName("linjer");
第一行用于清除代码前面的潜在错误消息。然后我尝试打开一个 XML 文件,因为我需要从中读取。
如您所见,我在那里输入了两个调试语句;他们将打印 1 或 2,具体取决于我在代码中的进展情况。
使用它,我发现它恰好在 Connect.send(null);
语句处停止(因为 1 被打印出来,但 2 从来没有),但我无法弄清楚为什么。 Google 说可能是 chrome 无法访问本地文件,但是当我找到允许 Chrome 执行此操作的方法时,它仍然不起作用。
我做错了什么?
最佳答案
这可能是一个同步问题,需要您的代码根本无法获得的响应。
尝试使用异步调用:
Connect.open("GET", "xmlTest.xml", true);
还要确保设置正确的回调,因为您现在将在此处使用异步而不是同步代码,如下所示:
// Global variable scope
var docX;
var linjer;
// Define your get function
getDoc = function(url, cbFunc) {
var Connect = new XMLHttpRequest();
// Perform actions after request is sent
// You'll insert your callback here
Connect.onreadystatechange = function() {
// 4 means request finished and response is ready
if ( Connect.readyState == 4 ) {
// Here is where you do the callback
cbFunc(Connect.responseXML);
}
};
// 'true' param means async, it is also the default
Connect.open('GET', url, true);
Connect.send();
}
// Define your callback function
callbackFunction = function(responseXML) {
// XML file can now be stored in the global variable
window.docX = responseXML;
window.linjer = window.docX.getElementsByTagName("linjer");
}
// And here is the call you make to do this
getDoc("xmlTest.xml", callbackFunction);
为了更好地理解所有这些,请对范围、闭包、回调和异步做一些研究>.
关于javascript - XMLHttprequest.send(null) 使我的代码崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33347248/