如何完成XMLHttpRequest

时间:2016-05-07 16:55:24

标签: ajax xml xml-parsing xmlhttprequest

我正在制作一种字典网页,我无法弄清楚如何使XMLHttpRequest正常工作。我需要将XML信息传输到html中的特定位置,id =“data”。我试图这样做,以便页面不必刷新。代码很乱我道歉。

<p> <!-- This is the button that will trigger the data appearing --> 
    <div id="div1" id="buttons" >
        <ul class="actions">
            <li><input type="button" id="ajaxButton" value="Traditional" class="special"/></li>
        </ul>
    </div>



<script type="text/javascript">
    (function () {
        var httpRequest;
        document.getElementById("ajaxButton").onclick = function() {
            var title = document.getElementById("data").value;
            makeRequest('data.xml', word)
        } 
    };

        function makeRequest(url, word) {
            httpRequest = new XMLRequst();

            if (!httpRequest) {
                alert('Giving up. Cannot create an XMLHTTP instance');
                 return false;
            }

            xmlhttp.onreadystatechange = contents; 
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                //contents(xmlhttp); 

            httpRequst.open("GET", url);
            httpRequest.send();
        }


        function contents() {
            if (xmlhttp.readyState == XMLHttpRequest.DONE) {
                if(xmlhttp.status == 200) {
        //This is where the XML should be sent to the HTML          
        }

</script>
<div id="data">

<!-- XML DATA WILL GO HERE POTENTIALLY -->

</div>

这是XML文件'data.xml'

<dictionary>
    <word>
        <title>Ubiquitous</title>
        <trad>This is the traditional defintion ubiquitous</trad>
        <simp>This is the simplified defintion hopefully ubiquitous</simp>
    </word>

    <word>
        <title>Lithe</title>
        <trad>This is the traditional defintion of lithe</trad>
        <simp>This is the simplified defintion of lithe hopefully</simp>
    </word>
</dictionary> 

1 个答案:

答案 0 :(得分:0)

您可能有兴趣在httpRequest.open(...)和httpRequest.send()之间包含一个异步函数,如下所示:

//f is your xml file
var fileURL = URL.createObjectURL(f);
httpRequest.open("GET", fileURL);
httpRequest.onload = function(){
    URL.revokeObjectURL(fileURL);
    populateHTML(this.responseXML);
};
httpRequest.send();

然后在方法外面创建populateHTML以操纵获得的内容:

function populateHTML(xmlDoc){
  var accessAtr = xmlDoc.getElementsByTagName("trad")[0].childNodes[0].nodeValue;//gets the content of first trad tag.

  //use accessAtr to continue writing your "data" id HTML content from here.
}