【问题标题】:How to complete XMLHttpRequest如何完成 XMLHttpRequest
【发布时间】:2016-05-14 07:21:16
【问题描述】:

我正在制作一种字典网页,但我不知道如何让 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> 

【问题讨论】:

    标签: ajax xml xml-parsing xmlhttprequest


    【解决方案1】:

    您可能有兴趣在 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.
    }
    

    【讨论】:

      猜你喜欢
      • 2013-08-21
      • 2020-02-06
      • 1970-01-01
      • 2013-08-18
      • 1970-01-01
      • 2012-04-30
      • 2021-03-07
      • 2021-02-15
      • 1970-01-01
      相关资源
      最近更新 更多