responseXML 显示为空,即使 xhr 对象将其显示为 set

responseXML displaying as null even though xhr object shows it as set

本文关键字:显示 set 对象 即使 responseXML xhr      更新时间:2023-09-26

我有以下代码最终填充一个表。此时,我创建了一个 XHR,加载时它将调用我的员工集合进程 XML 函数

EmployeeCollection.prototype.fetchXML = function(path, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", path, true);
    xhr.send();
    xhr.onload = this.processXML(xhr, callback);
};
EmployeeCollection.prototype.processXML = function(xhr, callback) {
     console.log(xhr); // this shows an XHR object with 
                       // readyState: 4 and responseXML: document
     console.log(xhr.responseXML); // null
}

我的问题是;如果我访问 xhr 对象并在控制台中展开节点,为什么我可以将 responseXML 视为文档,但当我尝试直接访问 xhr 对象的此属性时 - 我不能?

您遇到的问题是您正在调用该方法并将其返回的内容分配给 onload。因此,当您"同化"时,它会在 Ajax 调用实际加载之前调用该方法。

xhr.onload = this.processXML(xhr, callback);

它应该是

xhr.onload = this.processXML.bind(this, xhr, callback);

var that = this;
xhr.onload = function () { that.processXML(xhr, callback); };

原因可能是在浏览器开发人员工具中展开对象值时对对象值的评估。例如,目前您在console.lognull - 它在执行时已记录。

但是,在控制台窗口中展开值时(稍后)会评估提供document值的第二个console.log