A introdução assistida de resultados de pesquisa:Jquery executar função após getJSON concluída dentro de keyup função
Pergunta
Eu tenho lido um monte de respostas aqui sobre diferidos técnicas de getJSON/requisições em ajax, mas nada parece se encaixam no meu cenário.Eu estou fazendo uma pesquisa de entrada retornar um conjunto de resultados com base em um getJSON chamada depois de 4 caracteres.Isto é para limitar a quantidade de resultados retornados, e também a quantidade de requisições ajax (aberto a soluções mais eficazes).
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);
}
});
O problema que estou enfrentando é que se você digitar rapidamente, em 5 (mais do que 4) caracteres, o if(string.length > quiet_chars)
condição é atendida antes de $('.search_results').html('<ul>'+list_html+'</ul>');
foi executado, e informa ao usuário não há resultados de pesquisa.
Eu preciso atender o if(string.length > quiet_chars)
condição para continuar a filtragem de resultados retornados, mas só depois que a lista foi acrescentado para o DOM do getJSON pedido.Obrigado.
Solução 2
Tenho que trabalhar!
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)
}
}
});
A partir daqui: https://stackoverflow.com/questions/5280699#5291067
Se alguém está tentando obter algo semelhante, aqui está a minha resultados de pesquisa função:
//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');
}
}
Crédito para a case-insensitive versão :contains
vai para Rob Sawyer.
Outras dicas
editado para atender suas especificações
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);
}
});