Home  >  Q&A  >  body text

javascript - Ask a question about Ajax reading xml files?

xml file:

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <acc>
        <user>zhangsan</user>
        <psd>123456</psd>
    </acc>
    <acc>
        <user>lisi</user>
        <psd>654321</psd>
    </acc>
</urlset>

js code is as follows:

function showHint(str) {
        "user static";
        var xmlhttp  = new XMLHttpRequest();
        var psd_text = document.getElementById("psd_text");
        if (str.length == 0) {
            psd_text.innerHTML = "";
            return;
        }
        xmlhttp.open("GET", "acc.xml", true);
        xmlhttp.send();
        xmlhttp.onreadystatechange = function() {
            var acc_node = xmlhttp.responseXML.documentElement.getElementsByTagName("user");
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                for(var i = 0; i < acc_node.length; i++){
                    if(acc_node[i].firstChild.nodeValue.indexOf(str)){
                        psd_text.innerHTML = acc_node[i].lastChild.nodeValue;
                    }
                }
            }
        }
    }
    

html code is as follows:

<body>
    <h3>请在下面的输入框中输入用户名:</h3>
    <form>
        <label>用户名:</label><input type="text" id="user_input" value="" onkeyup="showHint(this.value)" />
    </form>
    <p>密码:<span id="psd_text"></span></p> 
</body>

I learned an example in w3school and wanted to change it to enter the user name, then search for the node containing the user name in the xml file, and finally display the password.

Google Chrome always reports an error: Cannot read property 'documentElement' of null.
And Firefox reported an error: xmlhttp.responseXML is null.
I haven’t been able to figure it out for a long time, so I came here to ask for help.

为情所困为情所困2734 days ago560

reply all(2)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-05-19 10:21:04

    The error reported in your code should be this sentence:

     var acc_node = xmlhttp.responseXML.documentElement.getElementsByTagName("user");

    The XMLHttpRequest.responseXML property is a read-only value that returns a Document containing the HTML or XML retrieved by the request, or null if the request was unsuccessful, has not been sent, or the retrieved data cannot be correctly parsed as XML or HTML. Source

    As mentioned above, the request was not successful at this time, so xmlhttp.responseXML is null, so an error will be reported. Try writing this code in the if statement that determines the ajax status.

    reply
    0
  • 漂亮男人

    漂亮男人2017-05-19 10:21:04

    Thank you very much, it has been solved. (Send flowers manually

    reply
    0
  • Cancelreply