Живой поиск и фильтр JavaScript - PullRequest
0 голосов
/ 30 апреля 2020

У меня есть страница только с панелью поиска; Я sh могу извлечь контент из API, отфильтровать его при вводе [search], а затем отобразить совпадения на странице. Больше похоже на то, что делает этот плагин: https://lscf.pixolette.com/photography/ Как мне этого добиться, пожалуйста?

В настоящее время у меня есть этот код. Что я делаю не так, пожалуйста?

const search = document.getElementById('search_box');
const searchResults = document.getElementById('search-results');
const searchMessage = document.getElementById('search-message');
let users;

// Get users
const getUsers = async () => {
const res = await fetch('baseUrl/wp-json/wp/v2/posts');
users = await res.json();
};

// FIlter states
const searchUsers = searchText => {
// Get matches to current text input
let matches = users.filter(user => {
    const regex = new RegExp(`^${searchText}`, 'gi');
    // return user.displayName.match(regex) || 
user.abbr.match(regex);
});

console.log(matches);
// Clear when input or matches are empty
if (searchText.length === 0) {
    matches = [];
    searchResults.innerHTML = '';
}

outputHtml(matches);

};

// Show results in HTML
const outputHtml = matches => {
if (matches.length > 0) {
    const html = matches.map(match =>
        `<div class="card card-body mb-1">
            <h4>${match.title.rendered} (${match.id}) 
            <span class="text-primary">${match.userPrincipalName}. 
 </span></h4>
            <small>ID: ${match.id} / Language: 
  ${match.preferredLanguage}</small>
        </div>`
    )
        .join('');
    searchResults.innerHTML = html;
  }
};

window.addEventListener('DOMContentLoaded', getUsers);
search.addEventListener('input', () => searchUsers(search.value));

1 Ответ

0 голосов
/ 30 апреля 2020

Пример использования WordPress API

Поле поиска



   <div>
    <h4>Search blog by title</h4>
            <div class="form-group ">
        <input type="text" name="search_box" id="search_box" class="form-control" placeholder="Search by slug e.g my-title" onfocus="this.value=''" >
      </div>
    </div>

РЕЗУЛЬТАТЫ ДИСПЛЕЯ


    <table id='results'>

    </table>

ПОИСК ПОЛЕ AJAX


    //setup before functions
    var typingTimer;                //timer identifier
    var doneTypingInterval = 5000;  //time in ms (5 seconds)



    //on keyup, start the countdown
    $('#search_box').keyup(function(){
        clearTimeout(typingTimer);
        if ($('#search_box').val()) {  
          var text = $('#search_box').val();    
            typingTimer = setTimeout(doneTyping(text), doneTypingInterval)
        }
    });

    //user is "finished typing," do something
    function doneTyping (text) {
      //do something

        // var text = text;

          var api_url_search = `/wordpress/wp-json/wp/v2/posts?slug=${text}`;

           $.ajax({
            url:api_url_search,
           dataType: 'json',
                success: function(response){
                     var len = response.length;                     
    for(var i=0; i<len; i++){
                        var id = response[i].id;
                        var date = response[i].date_gmt;
                        var slug = response[i].slug;
                        var excerpt = response[i].excerpt.rendered;
                        var categories = response[i].categories;

                        var search_str =
                         '<td>'+
                        '<div class="card" style="width: 300px;">' +
                         '<div class="card-divider">' + (i+1) + ' ' + slug + '</div>' +    

                        ' <div class="card-section">' +   
                         '<p>' + excerpt + '</p>' +
                         '<h4>' +  date + '</h4>' +
                         '<h4>' + 'Category:' + categories + '</h4>' +
                        '<a href="somepage.php?">'+ 
                        '<input type="button" value="read more">' + '</input>' +
                        ' </a>' +
                        ' </div>' +
                         '</div>'+
                           '</td>'           
                            ;

             $('#results').empty().append(search_str);
     } 
                }
     });
     };

...