从w3c看到的例子,自己测试了一下。ok。
js解析xml,暂时没有找到可以跨域的办法。跨域的话,只能通过后台去写。
javascript
<script type="text/javascript"> var xmlhttp; function loadXMLDoc(url) { xmlhttp = null; if (window.XMLHttpRequest) {// code for IE7, Firefox, Mozilla, etc. xmlhttp = new XMLHttpRequest(); } else if (window.ActiveXObject) {// code for IE5, IE6 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } if (xmlhttp != null) { xmlhttp.onreadystatechange = onResponse; xmlhttp.open("GET", url, true); xmlhttp.send(null); } else { alert("Your browser does not support XMLHTTP."); } } function onResponse() { if (xmlhttp.readyState != 4) return; if (xmlhttp.status != 200) { alert("Problem retrieving XML data"); return; } txt = "<table border='1'>"; x = xmlhttp.responseXML.documentElement.getElementsByTagName("item"); for (i = 0; i < x.length; i++) { txt = txt + "<tr>"; xx1 = x[i].getElementsByTagName("title"); { try { txt = txt + "<td>" + xx1[0].firstChild.nodeValue + "</td>"; } catch (er) { txt = txt + "<td> </td>"; } } xx2 = x[i].getElementsByTagName("content"); { try { txt = txt + "<td>" + xx2[0].firstChild.nodeValue + "</td>"; } catch (er) { txt = txt + "<td> </td>"; } } xx3 = x[i].getElementsByTagName("date"); { try { txt = txt + "<td>" + xx3[0].firstChild.nodeValue + "</td>"; } catch (er) { txt = txt + "<td> </td>"; } } txt = txt + "</tr>"; } txt = txt + "</table>"; document.getElementById('showhtml').innerHTML = txt; </script>
页面
<div id="showhtml"> <button οnclick="loadXMLDoc('1.xml')">Get xml information</button> </div>
1.xml
<?xml version="1.0" encoding="GBK" ?> <news> <item> <title>this is title</title> <content>this is content</content> <date>2013-12-10 13:50:44</date> </item> </news>