简体   繁体   中英

Can I use XMLHttpRequest to make a search bar?

Hi there I am working on a search bar I would like the search box to display p, li and h3 elements of various pages using XMLHttpRequest()? and how?

I am converting all these elements into an array but I don't know how to make sure that the array displays in the search box so that the user can click and be redirected to the element's page.

I am trying to learn javascript so please vanilla javascript only.

Thank you for your time, hope that makes sense.

 const search = document.getElementById("myInput"); const list = document.getElementById("list"); const sections = document.querySelectorAll("li, h3, p"); const filter = Array.prototype.filter; function setlist(group) { for (const item of group) { const it = document.createElement("li"); const text = document.createTextNode(item.name); it.appendChild(text); list.appendChild(it); } if (group.length === 0) {} } function clearList() { while (list.firstChild) { list.removeChild(list.firstChild); } } function setNoResults() { const it = document.createElement("li"); it.classList.add("list-group-item"); const text = document.createTextNode("no results found"); it.appendChild(text); list.appendChild(it); } function getRelevancy(value, searchTerm) { if (value === searchTerm) { return 2; } else if (value.startWith(searchTerm)) { return 1; } else if (value.includes(searchTerm)) { return 0; } else { return -1; } } search.addEventListener("input", event => { let value = event.target.value; if (value && value.length > 0) { value = value.toLowerCase(); setlist( sections.filter(item => { return item.name.includes(value); }).sort((itemA, itemB) => { return ( getRelevancy(itemB.name, value) - getRelevancy(itemA.name, value) ); }) ); } else { clearList(); } });
 <div class="navbar"> <ul class="navSection"> <li class="collection-item"> <a href="#Headphones"></a>Speakers</li> <li class="collection-item"><a href="#Headphones">Headphones</a></li> <li class="collection-item"><a href="#Accessories">Accessories</a></li> <li class="collection-item"><a href="#Earphones">Earphones</a></li> <li class="collection-item"><a href="#all">All</a></li> </ul> </div> <div class="basketSearch"> <div class="searchBar"> <input type="text" name="search" value="" autocomplete="off" id="myInput" placeholder="" /> </div> <ul class="listGroup" id="list"></ul>

You should have a Database with the data or use an API to fetch some. The second option is to have a JSON file locally that will contain the data.


    let request = new XMLHttpRequest();
    request.open('GET', 'URL*', true);

    request.onreadystatechange = function() {
        if (request.readyState === 4 && request.status === 200) {
            let data = JSON.parse(request.responseText)
        }
    };
    request.send(null);

 - Example of data -
 [
  {name: 'something', ...othervalues},
 ]

 OR

 ['something', 'item1', 'item2', ...]


*URL = The path to a php file, or url to an API.

After that you can use your

search.addEventListener("input", event => {...}) to filter the data array results. Have in mind that Ajax requests have an asynchronous nature and you have to handle them properly. You might consider using async functions or promises. Otherwise if you fire the input event before the result is set, the data will be undefined . An other way is to set your search.addEventListener("input", event => {...}) after the ajax request is finished

 request.onreadystatechange = function() {
        if (request.readyState === 4 && request.status === 200) {
            let data = JSON.parse(request.responseText);
            search.addEventListener("input", event => {...})
        }
    };

So you can have direct access to the data variable. Also an other option for the dropdown menu for the suggestions is HTML Datalists .

Cheers.

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