responseXML 显示为 null,即使 xhr 对象显示为已设置
responseXML displaying as null even though xhr object shows it as set
我有以下代码,它最终填充了 table。此时我创建了一个 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 对象的 属性 - 我可以'吨?
原因可能是您在浏览器开发人员工具中扩展对象值时对其进行了评估。例如,目前您的 console.log
中有 null
- 它已在执行时记录。
但是第二个 console.log
为您提供 document
值是在您在控制台 window 中展开时评估的(稍后)。
您遇到的问题是您正在调用该方法并将其 returns 分配给 onload。因此,当您 "assiging" 时,它会在 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); };
我有以下代码,它最终填充了 table。此时我创建了一个 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 对象的 属性 - 我可以'吨?
原因可能是您在浏览器开发人员工具中扩展对象值时对其进行了评估。例如,目前您的 console.log
中有 null
- 它已在执行时记录。
但是第二个 console.log
为您提供 document
值是在您在控制台 window 中展开时评估的(稍后)。
您遇到的问题是您正在调用该方法并将其 returns 分配给 onload。因此,当您 "assiging" 时,它会在 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); };