Résultats de recherche prédictifs :Jquery exécute la fonction une fois getJSON terminé dans la fonction keyup
Question
J'ai lu beaucoup de réponses ici sur les techniques différées sur les requêtes getJSON/ajax mais rien ne semble correspondre à mon scénario.Je fais en sorte qu'une entrée de recherche renvoie un ensemble de résultats basés sur un appel getJSON après 4 caractères.Il s'agit de limiter la quantité de résultats renvoyés, ainsi que la quantité de requêtes ajax (ouvertes à des solutions plus efficaces).
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);
}
});
Le problème spécifique auquel je suis confronté est que si vous tapez rapidement 5 (plus de 4) caractères, le if(string.length > quiet_chars)
la condition est remplie avant $('.search_results').html('<ul>'+list_html+'</ul>');
a été exécuté et indique à l'utilisateur qu'il n'y a aucun résultat de recherche.
Je dois rencontrer le if(string.length > quiet_chars)
condition pour continuer à filtrer les résultats renvoyés, mais seulement après que la liste a été ajoutée au DOM à partir de la requête getJSON.Merci.
La solution 2
Ça marche !
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)
}
}
});
D'ici: https://stackoverflow.com/questions/5280699#5291067
Si quelqu'un essaie de faire fonctionner quelque chose de similaire, voici ma fonction de résultats de recherche :
//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édit pour la version insensible à la casse de :contains
va à Rob Sawyer.
Autres conseils
édité pour répondre à vos spécifications
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);
}
});