Predicción de resultados de la búsqueda:Jquery ejecutar la función después de getJSON completa dentro de keyup función
Pregunta
He estado leyendo un montón de respuestas aquí sobre diferidos técnicas en getJSON/peticiones ajax, pero nada parece encajar mi escenario.Estoy haciendo una búsqueda de entrada devolver un conjunto de resultados basados en una getJSON llamada después de 4 caracteres.Esto es para limitar la cantidad de resultados que devuelve, y también la cantidad de peticiones ajax (abierto a soluciones más eficaces).
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);
}
});
El problema específico que me estoy enfrentando es si escribir rápidamente en 5 (más de 4) caracteres, el if(string.length > quiet_chars)
se cumple la condición de antes de $('.search_results').html('<ul>'+list_html+'</ul>');
se ha ejecutado, y se indica al usuario que no hay resultados de búsqueda.
Que se necesita para cumplir la if(string.length > quiet_chars)
condición para continuar el filtrado de los resultados devueltos, pero sólo después de la lista ha sido añadida a la catedral de la getJSON solicitud.Gracias.
Solución 2
Tengo trabajo!
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 de aquí: https://stackoverflow.com/questions/5280699#5291067
Si alguien está tratando de obtener algo de trabajo similares, he aquí los resultados de mi búsqueda de la función:
//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');
}
}
De crédito para el caso insensibles a la versión de :contains
va a Rob Sawyer.
Otros consejos
editado para que se ajuste a sus especificaciones
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);
}
});