javascript - AJAX 响应 XML 错误

标签 javascript ajax cross-browser

在发出 AJAX 请求和处理响应时,我遇到了一些奇怪的问题。

我正在对 xml 文件进行 ajax 调用。然而,当我得到响应时,xhr.responseText 属性在 firefox 中工作正常,但在 IE 中却不行。 另一件事是我正在尝试将 xhr.responseXML 作为 XMLDocument 访问,但它告诉我在 firefox 中它告诉我 xhr.responseXML 在 ie 中是未定义的,即它甚至没有向我显示未定义的错误或显示输出。

这是我用来发出请求的代码:

var ajaxReq = function(url, callback) {
    //initialize the xhr object and settings
    var xhr = window.ActiveXObject ?
            new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest(),
    //set the successful connection function
        httpSuccess = function(xhr) {
            try {
                // IE error sometimes returns 1223 when it should be 204
                //  so treat it as success, see XMLHTTPRequest #1450
                // this code is taken from the jQuery library with some modification.
                return !xhr.status && xhr.status == 0 ||
                        (xhr.status >= 200 && xhr.status < 300) ||
                        xhr.status == 304 || xhr.status == 1223;
            } catch (e) { }
            return false;
        };

    //making sure the request is created
    if (!xhr) {
        return 404; // Not Found
    }


    //setting the function that is going to be called after the request is made
    xhr.onreadystatechange = function() {
        if (!httpSuccess(xhr)) {
            return 503; //Service Unavailable
        }
        if (xhr.responseXML != null && xhr.responseText != null &&
                xhr.responseXML != undefined && xhr.responseText != undefined) {
            callback(xhr);
        }
    };


    //open request call
    xhr.open('GET', url, true);

    //setup the headers
    try {
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.setRequestHeader("Accept", "text/xml, application/xml, text/plain");
    } catch ( ex ) {
        window.alert('error' + ex.toString());
    }

    //send the request
    try {
        xhr.send('');
    } catch (e) {
        return 400; //bad request
    }

    return xhr;
};

这就是我调用函数来测试结果的方式:

window.onload = function() {
    ajaxReq('ConferenceRoomSchedules.xml', function(xhr) {
        //in firefox this line works fine,
        //but in ie it doesnt not even showing an error
        window.document.getElementById('schedule').innerHTML = xhr.responseText;
        //firefox says ''xhr.responseXML is undefined'.
        //and ie doesn't even show error or even alerts it.
        window.alert(xhr.reponseXML.documentElement.nodeName);
    });
}

这也是我第一次尝试使用 AJAX,所以可能有些地方我没有看对。 我一直在疯狂地寻找任何关于为什么或如何修复它的迹象,但没有运气。 任何想法都会很棒。

编辑:

我知道使用框架会更好,但老板不想添加仅用于 ajax 功能的框架(“只是”对于 ajax 来说不是一个公平的词 :P)。所以我用纯 javascript 来做。

XML 文件格式正确,我在网络浏览器中看到它很好,但为了完成,这是我正在使用的测试文件:

<?xml version="1.0" encoding="utf-8"?>
<rooms>
  <room id="Blue_Room">
    <administrator>somebody@department</administrator>
    <schedule>
      <event>
        <requester>
          <name>Johnny Bravo</name>
          <email>jbravo@department</email>
        </requester>
        <date>2009/09/03</date>
        <start_time>11:00:00 GMT-0600</start_time>
        <end_time>12:00:00 GMT-0600</end_time>
      </event>
    </schedule>
  </room>
  <room id="Red_Room">
    <administrator>somebody@department</administrator>
    <schedule>
    </schedule>
  </room>
  <room id="Yellow_Room">
    <administrator>somebody@department</administrator>
    <schedule>
    </schedule>
  </room>
</rooms>

编辑 2: 好消息是我说服了我的老板使用 jQuery,坏消息是 AJAX 仍然困扰着我。出于好奇,我会阅读更多有关它的信息。感谢您的提示,我将答案归功于 Heat Miser,因为他是最接近工作的提示。

最佳答案

几年前我遇到了同样的问题,然后我放弃了 responseXML 并开始始终使用 responseText。这个解析函数对我一直有效:

function parseXml(xmlText){
    try{
        var text = xmlText;
        //text = replaceAll(text,"&lt;","<");
        //text = replaceAll(text,"&gt;",">");
        //text = replaceAll(text,"&quot;","\"");
        //alert(text);
        //var myWin = window.open('','win','resize=yes,scrollbars=yes');
        //myWin.document.getElementsByTagName('body')[0].innerHTML = text;
        if (typeof DOMParser != "undefined") { 
            // Mozilla, Firefox, and related browsers 
            var parser=new DOMParser();
            var doc=parser.parseFromString(text,"text/xml");
            //alert(text);
            return doc; 
        }else if (typeof ActiveXObject != "undefined") { 
            // Internet Explorer. 
        var doc = new ActiveXObject("Microsoft.XMLDOM");  // Create an empty document 
            doc.loadXML(text);            // Parse text into it 
            return doc;                   // Return it 
        }else{ 
            // As a last resort, try loading the document from a data: URL 
            // This is supposed to work in Safari. Thanks to Manos Batsis and 
            // his Sarissa library (sarissa.sourceforge.net) for this technique. 
            var url = "data:text/xml;charset=utf-8," + encodeURIComponent(text); 
            var request = new XMLHttpRequest(); 
            request.open("GET", url, false); 
            request.send(null); 
            return request.responseXML; 
        }
    }catch(err){
        alert("There was a problem parsing the xml:\n" + err.message);
    }
}

使用这个 XMLHttpRequest 对象:

// The XMLHttpRequest class object

debug = false;

function Request (url,oFunction,type) {
    this.funct = "";
    // this.req = "";
    this.url = url;
    this.oFunction = oFunction;
    this.type = type;
    this.doXmlhttp = doXmlhttp;
    this.loadXMLDoc = loadXMLDoc;
}

function doXmlhttp() {
    //var funct = "";
    if (this.type == 'text') {
        this.funct = this.oFunction + '(req.responseText)';
    } else {
        this.funct = this.oFunction + '(req.responseXML)';
    }
    this.loadXMLDoc();
    return false;
}

function loadXMLDoc() {
    //alert(url);
    var functionA = this.funct;
    var req;
    req = false;

    function processReqChange() {
        // alert('reqChange is being called');
        // only if req shows "loaded"
        if (req.readyState == 4) {
            // only if "OK"
            if (req.status == 200) {
                // ...processing statements go here...
                eval(functionA);
                if(debug){
                    var debugWin = window.open('','aWindow','width=600,height=600,scrollbars=yes');
                    debugWin.document.body.innerHTML = req.responseText;
                }
            } else {
                alert("There was a problem retrieving the data:\n" +
                    req.statusText + '\nstatus: ' + req.status);
                if(debug){
                    var debugWin = window.open('','aWindow','width=600,height=600,scrollbars=yes');
                    debugWin.document.body.innerHTML = req.responseText;
                }
            }
            }
    }

    // branch for native XMLHttpRequest object
    if(window.XMLHttpRequest) {
        try {
            req = new XMLHttpRequest();
        } catch(e) {
            req = false;
        }
    // branch for IE/Windows ActiveX version
    } else if(window.ActiveXObject) {
        try {
                req = new ActiveXObject("Msxml2.XMLHTTP");
        } catch(e) {
                try {
                    req = new ActiveXObject("Microsoft.XMLHTTP");
                } catch(e) {
                    req = false;
                }
        }
    }



    if(req) {
        req.onreadystatechange = processReqChange;
        if(this.url.length > 2000){
            var urlSpl = this.url.split('?');
            req.open("POST",urlSpl[0],true);
            req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
            req.send(urlSpl[1]);
        } else {
            req.open("GET", this.url, true);
            req.send("");
        }
    }
}

function browserSniffer(){
    if(navigator.userAgent.toLowerCase().indexOf("msie") != -1){
        if(navigator.userAgent.toLowerCase().indexOf("6")){
            return 8;
        }else{
            return 1;
        }
    }
    if(navigator.userAgent.toLowerCase().indexOf("firefox") != -1){
        return 2;
    }
    if(navigator.userAgent.toLowerCase().indexOf("opera") != -1){
        return 3;
    }
    if(navigator.userAgent.toLowerCase().indexOf("safari") != -1){
        return 4;
    }
    return 5;
}

诚然,这是非常古老的代码,但它仍然适用于我几年前建立的网站。我同意其他人的看法,尽管我现在通常使用框架,所以我不必再使用这段代码或类似的东西。

您可以在 Request onreadystate 函数中忽略一些与拆分等有关的细节。如果请求的长度超过一定长度,它应该将请求转换为帖子,但我只是决定发帖总是更好。

关于javascript - AJAX 响应 XML 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1013582/

相关文章:

javascript - django 和backbone.js 问题

javascript - 使用 AJAX 提交帖子后,使用 AJAX 显示帖子

javascript - 使用 postmessage 发回消息

javascript - 使用 javascript 测试多个屏幕

javascript - React mixin 到组合重构

php - 通过 Javascript 将 PHP 注入(inject) Value 属性

ajax - 当计算机断开连接时,jQuery .ajax 调用显示成功。如何诱发ajax错误状态?

javascript - 为什么滚动时音频停止播放?

css - 如何修复 Windows 上异常字符的等宽间距?

javascript - javascript中的简单悬停和悬停问题