通过ajax调用将xml数据加载到html

时间:2017-10-21 11:59:40

标签: javascript html ajax xml

您好我正在尝试使用javascript和html开发投票应用程序。我尝试第一次从xml列表加载参议员。必须进行Ajax调用才能在html页面中加载选民的名字。如果应用程序不是第一次运行,则从本地存储参议员获取。问题是我编写了代码,通过从xml文件加载将参议员拖放到相应的框中。但是,一旦html页面加载,xml的选民就不会显示。 我附加了一个jsfiddle链接加上我的xml供你查看。

 xml file: partList.xml
 <senators>
<senator>
    <name>Barbara Boxer</name>
    <party>Democrat</party>
</senator>
<senator>
    <name>Diane Feinstein</name>
    <party>Democrat</party>
</senator>
<senator>
    <name>Al Franken</name>
    <party>Democrat</party>
</senator>
<senator>
    <name>Charles Schumer</name>
    <party>Democrat</party>
</senator>
<senator>
    <name>John Kerry</name>
    <party>Democrat</party>
</senator>

<senator>
    <name>Lamar Alexander</name>
    <party>Republican</party>
</senator>
<senator>
    <name>Kelly Ayotte</name>
    <party>Republican</party>
</senator>
<senator>
    <name>Scott Brown</name>
    <party>Republican</party>
</senator>
<senator>
    <name>Susan Collins</name>
    <party>Republican</party>
</senator>
<senator>
    <name>Orrin Hatch</name>
    <party>Republican</party>
</senator>

使用ajax调用将xml文件加载到html并存储在本地存储中以便下次使用本地存储的Javascript代码:

        function loadCandidates(fname) {
var xmlhttp;
var txt, xx, x, i, cname, cparty;
var jsonData = [];
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        txt = "";
        x = xmlhttp.responseXML.documentElement.getElementsByTagName(KEY);
        for (i = 0; i < x.length; i++) {

            txt = txt + "<li draggable='true' id=" + 'c' + i + '' + ">";
            xx = x[i].getElementsByTagName("name");
            {
                try {
                    txt += xx[0].firstChild.nodeValue + "</li>";

                    cname = xx[0].firstChild.nodeValue;

                }
                catch (er) {
                    txt = txt + "<li>ffff</li>";
                }
            }
            xx = x[i].getElementsByTagName("party");
            {
                try {

                    cparty = xx[0].firstChild.nodeValue;
                }
                catch (er) {
                    txt = txt + "<li>ffff</li>";
                }
            }
            //Creates a json object to store
            jsonData.push({"name": cname, "party": cparty, "vote": "false"});

        }

        storeToLocal(jsonData);
        document.getElementById('members').innerHTML = txt;
        document.getElementById('msg').innerHTML = "Loaded "+ x.length+" candidates from AJAX";
    }
}
xmlhttp.open("GET", fname, true);
xmlhttp.send();

}

https://jsfiddle.net/q01e2bam/

0 个答案:

没有答案