处理服务器XML响应

时间:2015-01-20 00:02:25

标签: javascript ajax xml

所以我正在学习考试,而且我只有一个快速的问题,一直困扰着我。我使用AJAX获取XML文件来解析它并将其值插入到select元素中。这是代码:

<html>  
    <head>  
    </head>
    <body>  
        <button onclick="EnviaPedido()">Submeter</button>       
        <select id="select"></select>   

        <script type="text/javascript">             
                var xmlHttpObj;
                function CreateXmlHttpRequestObject() { 
                    if (window.XMLHttpRequest) {
                        xmlHttpObj = new XMLHttpRequest() 
                    }
                    else if (window.ActiveXObject) {
                        xmlHttpObj = new ActiveXObject("Microsoft.XMLHTTP")
                    }
                    return xmlHttpObj;          
                }

                function EnviaPedido() {
                    xmlHttpObj = CreateXmlHttpRequestObject();
                    xmlHttpObj.open("POST", "agenda.xml", true);
                    xmlHttpObj.onreadystatechange = ProcessaReposta;
                    xmlHttpObj.send();          
                }

                function ProcessaReposta() {
                    if (xmlHttpObj.readyState == 4 && xmlHttpObj.status == 200) {
                        var response = xmlHttpObj.responseText;

                        var xmlDoc;

                        if (window.DOMParser) {
                            parser = new DOMParser();
                            xmlDoc = parser.parseFromString(response, "text/xml");
                        } else {
                            xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                            xmlDoc.async = false;
                            xmlDoc.loadXML(response);
                        }

                        var select = document.getElementById("select");

                        var centrosInvestigacao = xmlDoc.getElementsByTagName("centro_de_investigacao");

                        for(i = 0; i < centrosInvestigacao.length; i++) {
                            var option = document.createElement("option");
                            option.innerHTML = centrosInvestigacao[i].childNodes[1].textContent;
                            select.appendChild(option);
                        }
                    }   
                }       
            </script>   
        <body>      
    </html>

这是返回的XML:

    <FCT>
      <centro_de_investigacao id="1">
        <nome>GECAD</nome>
        <local>ISEP</local>
        <classificao>Muito bom</classificao>
      </centro_de_investigacao>
      <centro_de_investigacao id="2">
        <nome>DEF</nome>
        <local>ISEP</local>
        <classificao>Bom</classificao>
      </centro_de_investigacao>
      <centro_de_investigacao id="3">
        <nome>ABC</nome>
        <local>FEUP</local>
        <classificao>Muito mau</classificao>
      </centro_de_investigacao>
    </FCT>

所以,当我想获得“nome&#39;为什么我必须使用

option.innerHTML = centrosInvestigacao[i].childNodes[1].textContent;

而不是

option.innerHTML = centrosInvestigacao[i].childNodes[0].textContent;

我知道这可能是一个愚蠢的问题,但它开始让我不知道这是不是预期的行为,或者我是不是以某种方式搞砸了。

感谢。

1 个答案:

答案 0 :(得分:1)

我做了一个小问题,也显示了部分答案。我认为您解析的XML文档的编码是“关闭”的,因为您的childNodes的第一个元素实际上是centro_de_investigacao的最后一个引用之间的文本节点。和&lt; nome。

的开始标记

如果检查剪辑集(例如你可以使用索引参数),你会发现第一个按钮不需要将索引增加到1,但是可以按照预期的方式使用第一个元素,nl一个在索引0。

因此,从XML文档中删除空格,你应该没问题。

空格:制表符,空格,换行符

// mocked, no real data
var xmlHttpObj;

function CreateXmlHttpRequestObject() {
  
  function Mock() {
    this.callready = function() {
      this.readyState = 4;
      this.status = 200;
      this.statusMsg = "OK";
      if (this.onreadystatechange && this.onreadystatechange.call) {
        setTimeout(this.onreadystatechange.bind(this), 0);
      }
    };
    
    this.open = function(methodType, url, async) {
      var el = document.getElementById('dataXml-' + url.split('.')[0]),
          content = el ? el.innerHTML : '';
      if (typeof async === 'undefined' || async) {
        // no action till send is executed
        this.responseText = content;
        this.responseXml = content;
        return;
      }
      return content;
    };
      
    this.send = function(data) {
        this.callready();
    };
  }
  return new Mock();
}

function EnviaPedido(index, url) {
  xmlHttpObj = CreateXmlHttpRequestObject();
  xmlHttpObj.open("POST", url, true);
  xmlHttpObj.onreadystatechange = ProcessaReposta.bind(this, index);
  xmlHttpObj.send();
}

function ProcessaReposta(index, url) {
  if (xmlHttpObj.readyState == 4 && xmlHttpObj.status == 200) {
    var response = xmlHttpObj.responseText;

    var xmlDoc;

    if (window.DOMParser) {
      parser = new DOMParser();
      xmlDoc = parser.parseFromString(response, "text/xml");
    } else {
      xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
      xmlDoc.async = false;
      xmlDoc.loadXML(response);
    }

    var select = document.getElementById("select");

    var centrosInvestigacao = xmlDoc.getElementsByTagName("centro_de_investigacao");
    select.options = [];

    for (i = 0; i < centrosInvestigacao.length; i++) {
      var option = new Option();
      var item = centrosInvestigacao[i].childNodes[index];
      option.text = item.textContent;
      select.options[i] = option;
    }
  }
}
<template id="dataXml-agenda"><FCT><centro_de_investigacao id="1"><nome>GECAD</nome><local>ISEP</local><classificao>Muito bom</classificao></centro_de_investigacao><centro_de_investigacao id="2"><nome>DEF</nome><local>ISEP</local><classificao>Bom</classificao></centro_de_investigacao><centro_de_investigacao id="3"><nome>ABC</nome><local>FEUP</local><classificao>Muito mau</classificao></centro_de_investigacao></FCT></template>
<template id="dataXml-original-agenda"><FCT>
<centro_de_investigacao id="1">
  <nome>GECAD</nome>
  <local>ISEP</local>
  <classificao>Muito bom</classificao>
</centro_de_investigacao>
<centro_de_investigacao id="2">
  <nome>DEF</nome>
  <local>ISEP</local>
  <classificao>Bom</classificao>
</centro_de_investigacao>
<centro_de_investigacao id="3">
  <nome>ABC</nome>
  <local>FEUP</local>
  <classificao>Muito mau</classificao>
</centro_de_investigacao>
</FCT></template>
<select id="select"></select>
<button id="btnGenerate" type="button" onclick="EnviaPedido(0, 'agenda.xml');">Get info</button>
<button id="btnGenerate" type="button" onclick="EnviaPedido(1, 'original-agenda.xml');">Get info false contentType</button>