Risultati di ricerca predittivi: funzione di esecuzione jquery dopo GetJson completa la funzione di tastiera

StackOverflow https://stackoverflow.com//questions/22056911

  •  22-12-2019
  •  | 
  •  

Domanda

Ho letto molte risposte qui sulle tecniche differite sulle richieste di GetJson / Ajax, ma nulla sembra adattare il mio scenario.Sto facendo un ingresso di ricerca restituire un insieme di risultati in base a una chiamata GetJson dopo 4 caratteri.Questo è limitare la quantità di risultati restituiti e anche la quantità di richieste AJAX (aperta a soluzioni più efficaci).

search_input.on('keyup', function() {

    var string       = $(this).val();
    var quiet_chars  = 4;

    if(string.length < quiet_chars) {

        // Simple notifications function which passes a message to a div, and optional class
        notification('Type '+(quiet_chars - string.length)+' more characters to search');
    }
    if(string.length == quiet_chars) {
        notification('Searching...', 'loading');
        $.getJSON('stores/stores-search/'+string, function(data) {

            // Loop through data and build list....
            $('.search_results').html('<ul>'+list_html+'</ul>');

            // Function which shows/hides list items based on Jquery :contains
            searchResults(string);

        });
    }
    if(string.length > quiet_chars) {
        searchResults(string);
    }

});
.

Il problema specifico che sto affrontando è se digiti rapidamente 5 (più di 4) caratteri, la condizione if(string.length > quiet_chars) viene soddisfatta prima che $('.search_results').html('<ul>'+list_html+'</ul>'); abbia eseguito e dice all'utente non ci sono risultati di ricerca.

Devo soddisfare la condizione if(string.length > quiet_chars) per continuare a filtrare i risultati restituiti, ma solo dopo che l'elenco è stato aggiunto al DOM dalla richiesta GetJSon.Grazie.

È stato utile?

Soluzione 2

ha capito!

var json_success = false,
    ajax_term;

function searchJson(string) {
    ajax_term = string;
    notification('Searching...', 'loading');
    $.getJSON('stores/stores-search/'+string, function(data) {

        // Loop through data and build list....
        $('.search_results').html('<ul>'+list_html+'</ul>');
        searchResults(string);
        json_success = true; 

    });
}

search_input.on('keyup', function() {

    var string       = $(this).val();
    var quiet_chars  = 4;

    if(string.length < quiet_chars) {
        json_success = false;
        notification('Type '+(quiet_chars - string.length)+' more characters to search');
    } else {

        if(json_success !== false || string.substr(0,4) !== ajax_term) {
            $.when(searchJson(string)).then(searchResults(string))
        } else {
            searchResults(string)
        }
    }
});
.

Da qui: https://stackoverflow.com/questions/5280699#5291067

Se qualcuno sta cercando di ottenere qualcosa di simile funzionante, ecco i miei risultati della ricerca Funzione:

//extends :contains to be case insensitive
$.extend($.expr[':'], {
    'containsi': function(elem, i, match, array) {
        return (elem.textContent || elem.innerText || '').toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
    }
});

// Instant search results
function searchResults(searchTerm) {

    var searchSplit = searchTerm.replace(/ /g, "'):containsi('");

    $(".search_results .tile").not(":containsi('" + searchSplit + "')").each(function() {
        $(this).addClass('hide').removeClass('show');
    });
    $(".search_results .tile:containsi('" + searchSplit + "')").each(function() {
        $(this).removeClass('hide').addClass('show');
    });

    var resultCount = $('.search_results .show').length;

    if(resultCount != '0') {
        notification('Showing '+resultCount+' results');
    } else {
        notification('No results', 'error');
    }
}
.

Credito per la versione Case-Insensitive di :contains va a Rob Sawyer .

Altri suggerimenti

Modificato per adattarsi alle tue specifiche

bool dataLoaded = false; //this is a global variable we have outside of the scope of the search_input.on function
search_input.on('keyup', function() {

    var string       = $(this).val();
    var quiet_chars  = 4;

    if(string.length < quiet_chars) {
        //let's reset the dataLoaded flag if the user ends up deleting characters and what not
        if(dataLoaded)
           dataLoaded = !dataLoaded;
        // Simple notifications function which passes a message to a div, and optional class
        notification('Type '+(quiet_chars - string.length)+' more characters to search');
    }
    if(string.length == quiet_chars) {
        notification('Searching...', 'loading');
        $.getJSON('stores/stores-search/'+string, function(data) {

            // Loop through data and build list....
            $('.search_results').html('<ul>'+list_html+'</ul>');
            dataLoaded = true;
            // Function which shows/hides list items based on Jquery :contains
            searchResults(string);

        });
    }
    else if(dataLoaded){
        searchResults(string);
    }


});
.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top