Результаты прогнозируемого поиска:Функция запуска Jquery после завершения getJSON в функции keyup

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

  •  22-12-2019
  •  | 
  •  

Вопрос

Я читал здесь много ответов об отложенных методах запросов getJSON/ajax, но, похоже, ничто не соответствует моему сценарию.Я делаю ввод поиска, возвращающий набор результатов на основе вызова getJSON после 4 символов.Это сделано для ограничения количества возвращаемых результатов, а также количества запросов ajax (открыто для более эффективных решений).

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);
    }

});

Конкретная проблема, с которой я столкнулся, заключается в том, что если вы быстро вводите 5 (более 4) символов, if(string.length > quiet_chars) условие выполняется раньше $('.search_results').html('<ul>'+list_html+'</ul>'); выполнился и сообщает пользователю, что результатов поиска нет.

мне нужно встретиться с if(string.length > quiet_chars) условие для продолжения фильтрации возвращаемых результатов, но только после того, как список был добавлен в DOM из запроса getJSON.Спасибо.

Это было полезно?

Решение 2

Получилось, работает!

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)
        }
    }
});

Отсюда: https://stackoverflow.com/questions/5280699#5291067

Если кто-то пытается заставить что-то подобное работать, вот моя функция результатов поиска:

//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');
    }
}

Благодарность за версию без учета регистра :contains идет в Роб Сойер.

Другие советы

отредактировано в соответствии с вашими требованиями

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);
    }


});
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top