Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

128
Views
La búsqueda en vivo de AJAX es súper lenta

Editar: estoy usando XAMPP con Apache incorporado, vscode

Hago una entrada de búsqueda en vivo (html>js>php>js>html), funciona sin problemas en la primera entrada, pero se vuelve cada vez más lenta cuando elimino y vuelvo a teclear, me pregunto qué está causando la demora y cómo arreglalo.

Y tengo una pregunta, para este ejemplo, ¿es mejor usar jquery o javascript puro?

Gracias

html

 <div> <input type="text" class="search" placeholder="find..." autocomplete="off" autocapitalize="characters"> <div class="result"></div> </div>

js

 $(document).ready(function(){ $(document).on("keyup input",".search",function(){ var input = $(this).val(); var result = $(this).next(".result"); if(input.length){ $.get("table.php", {term: input}).done(function(data){ result.html(data); }); } else{ result.empty(); } }); });

php

 <?php $link = mysqli_connect("localhost", "root", "******", "crypto"); // Check connection if($link === false){ die("ERROR: " . mysqli_connect_error()); } if(isset($_REQUEST["term"])){ $coin = "show tables from crypto where Tables_in_crypto LIKE ?"; //prepare the statement if($prepare = mysqli_prepare($link, $coin)){ // Bind variables to the prepared statement as parameters mysqli_stmt_bind_param($prepare, "s", $param_term); // Set parameters $param_term = $_REQUEST["term"] . '%'; // Attempt to execute the prepared statement if(mysqli_stmt_execute($prepare)){ $result = mysqli_stmt_get_result($prepare); // Check number of rows in the result set if(mysqli_num_rows($result) > 0){ // Fetch result rows as an associative array while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){ echo "<p>" . $row["Tables_in_crypto"] . "</p>"; } } else{ echo "<p>no result</p>"; } } else{ echo "ERROR: $coin. " . mysqli_error($link); } } // Close statement mysqli_stmt_close($prepare); } // close connection mysqli_close($link); ?> <script type="text/javascript" src="data.js"></script>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

JavaScript

  • No use "keyup input" , use solo el Evento "input" .
  • Recorta $(this).val().trim() tus valores de entrada , ¡no quieres un espacio vacío para activar una búsqueda de datos!
  • ¡Enfriarse! No desea realizar una solicitud adicional de AJAX ( $.get() ) mientras ya hay una en camino. En su lugar, cree un acelerador setTimeout que, solo una vez que el usuario dejó de escribir durante N milisegundos, se activará la solicitud.
    Una lógica de pseudocódigo para imaginarlo es bastante simple:
 jQuery($ => { // DOM ready and $ alias in scope const search = ($input) => { const input = $input.val().trim(); // Trim your strings! const $result = $input.next(".result"); if (!input) { $result.empty(); return; // end it here } $.get("table.php", {term: input}).done((data) => { console.log(data); // Exercise for the reader: // Make sure data is an Object // create "<p>" elements with text and populate $result }); }; let searchCooldown; // Search input cooldown $(document).on("input", ".search", function() { clearTimeout(searchCooldown); // clear occurring search timeout searchCooldown = setTimeout(() => { search($(this)); // will be triggered once user stops typing for 300ms }, 300); // 300ms seems like a good typing timeout?! }); });
  • No, no necesitas jQuery. La API Fetch es lo suficientemente madura.

PHP

  • No coloque etiquetas <script> dentro de un archivo PHP, cuyo único trabajo debería ser consultar los datos de una base de datos y devolverlos.
  • ¡No devuelva HTML desde PHP ! Eso es un desperdicio. Es posible que desee un archivo PHP para devolver datos JSON en su lugar ; de esa manera, puede ser utilizado por su página HTML, su reloj, refrigerador, etc. Por lo general, se hace usando echo json_encode($result); . Si necesita adjuntar también una propiedad de "error" a su JSON de datos de $result , hágalo.
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!