2009-06-18 91 views
3

当谈到创建AJAX请求和处理响应时,我一直有一些奇怪的问题。AJAX响应XML错误

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

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

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功能(“只是”不是阿贾克斯公平的一句话: P)。所以我正在用纯JavaScript来做。

XML文件格式良好的,我看到它在Web浏览器很好,但完成这是我使用的测试文件:

<?xml version="1.0" encoding="utf-8"?> 
<rooms> 
    <room id="Blue_Room"> 
    <administrator>[email protected]</administrator> 
    <schedule> 
     <event> 
     <requester> 
      <name>Johnny Bravo</name> 
      <email>[email protected]</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>[email protected]</administrator> 
    <schedule> 
    </schedule> 
    </room> 
    <room id="Yellow_Room"> 
    <administrator>[email protected]</administrator> 
    <schedule> 
    </schedule> 
    </room> 
</rooms> 

编辑2: 那么好消息是我说服我的老板使用jQuery,坏消息是AJAX仍然困扰着我。为了好奇,我会详细阅读它。感谢提示,我给了热吝啬的答案,因为他是最接近的工作提示。

回答

4

几年前我有同样的问题,然后我放弃了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函数中忽略拆分等的一些细节。如果它的长度超过一定长度,它应该将请求转换为帖子,但我只是认为做一个帖子总是更好。

1

我可以建议你看看隐藏和管理这些跨浏览器问题的框架(以可靠的方式)。这里的好处是jQuery。自己做这些事情会变得相当困难和复杂。

This可能是你需要的。

//编辑: 这是w3school如何显示它:

function ajaxFunction() 
{ 
var xmlhttp; 
if (window.XMLHttpRequest) 
    { 
    // code for IE7+, Firefox, Chrome, Opera, Safari 
    xmlhttp=new XMLHttpRequest(); 
    } 
else if (window.ActiveXObject) 
    { 
    // code for IE6, IE5 
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
else 
    { 
    alert("Your browser does not support XMLHTTP!"); 
    } 
} 
+0

这是一个很好的建议。让图书馆担心跨浏览器问题。 – 2009-06-18 16:10:42

+0

我同意,我已经使用jQuery,但如果我们要使用ajax,我的老板不想用整个框架填充网站。所以我必须自己做。尽管我仍然试图说服他使用框架。 – 2009-06-18 16:32:05

+0

@Tony L.,告诉他jQuery是一个脚本,而不是一个框架。框架听起来很重。 – 2009-06-18 16:54:48

0

为了避免您的跨浏览器的问题(并保存自己的编码了很多的项目,一个强大的社区已经开发,测试,并审查),你应该选择一个JavaScript库。 JQuery和Dojo是很好的选择。

1

您是否调用相对于当前文档的URL?由于IE浏览器将使用ActiveXObject的,它可能需要一个绝对路径,例如:

http://some.url/ConferenceRoomSchedules.xml

对于XML,你确定它的良好形成的呢?例如,它是否加载到XML编辑器中?

0

我相信你的网络服务器需要用'ConferenceRoomSchedules.xml'来提供正确的响应标题,例如: Content-Type:text/xml或任何其他xml类型。

3

当浏览器错误检测到内容类型或未正确发送内容类型时,会发生此问题。

它容易,只需将其覆盖:

var request = new XMLHttpRequest(); 
request.open("GET", url, false); 
request.overrideMimeType("text/xml"); 
request.send(null); 
return request.responseXML; 

不知道为什么......只有Safari和Chrome出现此问题(WebKit浏览器,服务器发送正确的头)。

0

Aron在https://stackoverflow.com/a/2081466/657416提供的答案是我认为最简单(也是最好)的答案。这是我的工作代码:

ajax = ajaxRequest(); 
ajax.overrideMimeType("text/xml"); 
ajax.open("GET", myurl;