通过javascript将XMLHttpRequest输出到DIV

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

标签: javascript html ajax json

我试图通过纯JS中的API调用列出本地传输系统的站名。我想循环遍历电台名称(其中45个)并将它们输出到 div id =“stationDiv”

内的列表中

我得到的是div中列出的45个空对象元素的列表。我似乎无法正确输出循环。

XML文件样本

<root>
<uri>
<![CDATA[ http://api.bart.gov/api/stn.aspx?cmd=stns ]]>
</uri>
<stations>
<station>
<name>12th St. Oakland City Center</name>
<abbr>12TH</abbr>
<gtfs_latitude>37.803664</gtfs_latitude>
<gtfs_longitude>-122.271604</gtfs_longitude>
<address>1245 Broadway</address>
<city>Oakland</city>
<county>alameda</county>
<state>CA</state>
<zipcode>94612</zipcode>
</station>
//44 more station's below this

设置调用API:

var URL ="http://api.bart.gov/api/stn.aspx?cmd=stns&key=MW9S-E7SL-26DU-VV8V"; //public key used
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

xmlhttp.open("GET",URL,false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML; 

if(xmlhttp.status == 200) {
    console.log("connection successful");
} else {
    console.log("server returned a status code of " + oHttp.status);
}

循环不起作用:

var x1=xmlDoc.getElementsByTagName("station");

function postNames(station) {
    var x = station.length;
    var n = 0;
    var element = document.getElementById('stationDiv');
    var html = '<ul>';
    while(n < x) {
      html += '<li>' + station[n] + '</li>';
      n++;
    }
    html += '</ul>';
    element.innerHTML = html;
}

postNames(x1);

提前谢谢,我有多本书和20张标签在我面前打开,但似乎无法正确输出。

只有PURE JS。

1 个答案:

答案 0 :(得分:0)

试试这个......

var x1=xmlDoc.getElementsByTagName("station");

var postNames = function(station) {
    var x = station.length;
    var n = 0;
    var element = document.getElementById('stationDiv');
    var html = '<ul>';
    while(n < x) {
      html += '<li>' + station[n].getElementsByTagName("name")[0].childNodes[0].nodeValue + '</li>';
      n++;
    }
    html += '</ul>';
    element.innerHTML = html;
}

postNames(x1);