XMLHttpRespone为空且状态为0

时间:2013-12-21 14:54:16

标签: javascript xml-parsing xmlhttprequest

我正在尝试使用以下代码解析来自java脚本的XML文档

var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function () {

        if (this.responseXML != null) {
            Caption(this.video, this.responseXML);
        } else {
            throw new Error("Can't read resource");
        }

    };
    xhr.video = obj;

    xhr.open("GET", "Br001.xml", true);
    xhr.send("");

但我得到status=0responseXML = NULL

随访:

在更改onreadystatechange后,我正在准备readyState = 1和status = 0,responsexml = NULL并且只获得一个回调

xhr.onreadystatechange = function () {
    if (this.readyState == 4
    && this.status == 200) {

    if (this.responseXML != null) {
        Caption(this.video, this.responseXML);
    } else {
        throw new Error("Can't read resource");
    }
    }
};

1 个答案:

答案 0 :(得分:3)

在响应可用之前,

readyState会经历多个阶段。您必须等待readyState更改为4

xhr.onreadystatechange = function () {

    if (this.readyState === 4) {
        if (this.responseXML != null) {
            Caption(this.video, this.responseXML);
        } else {
            throw new Error("Can't read resource");
        }
    }

};

最好检查status(例如,确保它是200 <= status < 300(因为2xx是“确定”回复),尽管您的this.responseXML != null可能已经足够用于此用途