为什么我在 JavaScript 中读取 XML 文件时得到空结果

Why am I getting a null result when reading an XML file in JavaScript?

本文关键字:结果 文件 XML JavaScript 读取 为什么      更新时间:2023-09-26

我有以下代码:

function loadXMLDoc() {
        var xhr = XMLHttpRequest();
        xhr.onreadystatechange = function () {
            //read the file and get results
            getDomicilesFromXML(xhr); //separate function (this is not the problem)
        };
        xhr.open('GET', TheXMLFile.xml', false);
        xhr.send();
    }

此函数在网页的初始化函数中调用。"TheXMLFile"是位于我网站的根项目目录中的XML文件。它似乎没有读取文件,因为结果始终为 null。我错过了什么吗?

准备好读取响应之前,onreadystatechange反复触发几次。您需要检查xhr.readyState以查看它是否已准备就绪,status查看它是否成功。

xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
        if (xhr.status == 0 || (xhr.status >= 200 && xhr.status < 300)) {
            //read the file and get results
            getDomicilesFromXML(xhr); //separate function (this is not the problem)
        }
    }
};

xhr.status == 0是一种解决方法,我不确定这些天我们仍然需要,一些浏览器[过去?]使用缓存的响应来做到这一点。


我建议从您的open电话中删除false。强制 HTTP 请求同步几乎从来都不是必需的,并且在请求期间会锁定浏览器的 UI。