简体   繁体   中英

How do I check if an input value exists on a xml file [Javascript and XML]

I was testing some stuff with HTML, JS and XML files and I had some questions. One of them was: How do I check if a given input by user exists on a xml file.

What I wanted to do was to get the value from the input "username" and check if it exists on the XML file. So I created a variable called username and gave it the value from the input. Then I used a for loop to loop by each line of the xml file to look for the username. Even typing "username1" on the input it doesnt alert me with "FOUND!".

Ps. : The file names are right. Its name is "data.xml".

This is my HTML file:

<form>
    <input type="text" id="username"/>
    <input type="password" id="password"/>
    <button onclick="checkID">SUBMIT</button>
</form>
    <script>
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", "data.xml", false);
        xmlhttp.send();
        var xmlDoc = xmlhttp.responseXML;

        var x = xmlDoc.getElementsByTagName("USER");

        function checkID() {
            var username = document.getElementsById("username").value;
            for(i = 0; i < x.length; i++) {
                toCHECK = x[i].getElementsByTagName("NAME")[0].childNodes[0].nodeValue;
                if(username === toCHECK) {
                    alert("FOUND!");
                }
            }
        }
    </script>

And this is my XML File:

<?xml version="1.0" encoding="UTF-8"?>
<USERS>
    <USER>
        <NAME>username1</NAME>
    </USER>
</USERS>

您可以使用indexOf ,如果返回-1,则输入不在您的字符串中,否则。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM