Mysql
 sql >> Database >  >> RDS >> Mysql

JQuery KeyUp Ricerca in tempo reale. Come?

Prova questo codice js al posto di quello che hai. Ho aggiunto la funzione di ritardo in modo che lo script attenda un determinato periodo di tempo dopo che l'utente smette di digitare prima di inviare la richiesta. Ciò impedisce che una grande quantità di richieste venga inviata al server.

<script type="text/javascript">
var delay = (function() {
  var timer = 0;
  return function(callback, ms){
    clearTimeout (timer);
    timer = setTimeout(callback, ms);
  };
})();

$("#search-box").keyup(
    function () {
        delay(function () {
            var keyword = $("#search-box").val();
            var URL = encodeURI("search.php?q=" + keyword);
            $.ajax({
                url: URL,
                cache: false,
                type: "GET",
                success: function(response) {
                    $("#results").html(response);
                }
            });
        }, 500);
    }
);
</script>