Skip to content

Instantly share code, notes, and snippets.

@itarocha
Last active May 31, 2017 01:59
Show Gist options
  • Save itarocha/e784aac35047ccd25a22ed8a56f557e0 to your computer and use it in GitHub Desktop.
Save itarocha/e784aac35047ccd25a22ed8a56f557e0 to your computer and use it in GitHub Desktop.
Autocomplete javascript de um texto via ajax com delay
var oldValor = "";
var xhr;
function trata(data) {
//var json = JSON.parse(data);
console.log("tratando....");
var options = $("#options");
$(options).empty();
var json = data;
$.each(json, function(i, item) {
var obj = json[i];
$(options).append("<li>" + obj.nome + "</li>");
});
};
$(function(){
var oldValor = "";
$('#searchString').keyup(function(e) {
clearTimeout($.data(this, 'timer'));
if (e.keyCode == 13)
search(true);
else
$(this).data('timer', setTimeout(search, 300));
});
function search(force) {
var existingString = $("#searchString").val();
if (existingString == oldValor) {
return;
}
oldValor = existingString;
console.log("search. force = "+force+". texto = "+existingString);
//if (!force){ return; }
//GET
/*
$.get('/consulta/busca?valor=' + existingString, function(data) {
console.log("foi");
trata(data);
});
*/
//POST
var limite = 15;
$.ajax({
url: '/consulta/buscaPost',
type: 'POST',
data: {valor : existingString, limite: limite},
success: function(data) {
trata(data);
}
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment