dongtan8122 2016-12-19 10:13
浏览 53
已采纳

AJAX - 尝试使用去抖动实现实时搜索

I tried to implement AJAX live search with AJAX and I did it quite well. Then I tried to add the _.debounce function so it will not overloads the server but it didn't work well..

this is the code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>PHP Live MySQL Database Search</title>
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $('.search-box input[type="text"]').on("keyup input", _.debounce(function(){
                /* Get input value on change */
                var term = $(this).val();
                var resultDropdown = $(this).siblings(".result");
                if(term.length){
                    $.get("backend-search.php", {query: term}).done(function(data){
                        // Display the returned data in browser
                        resultDropdown.html(data);
                    });
                } else{
                    resultDropdown.empty();
                }
            }),250);

            // Set search input value on click of result item
            $(document).on("click", ".result p", function(){
                $(this).parents(".search-box").find('input[type="text"]').val($(this).text());
                $(this).parent(".result").empty();
            });
        });
    </script>
</head>
<body>
<div class="search-box">
    <input type="text" autocomplete="off" placeholder="Search country..." />
    <div class="result"></div>
</div>
</body>
</html>

and this is the php file:

<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");

// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}

// Escape user inputs for security
$query = mysqli_real_escape_string($link, $_REQUEST['query']);

if(isset($query)){
    // Attempt select query execution
    $sql = "SELECT * FROM countries WHERE name LIKE '" . $query . "%'";
    if($result = mysqli_query($link, $sql)){
        if(mysqli_num_rows($result) > 0){
            while($row = mysqli_fetch_array($result)){
                echo "<p>" . $row['name'] . "</p>";
            }
            // Close result set
            mysqli_free_result($result);
        } else{
            echo "<p>No matches found for <b>$query</b></p>";
        }
    } else{
        echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
    }
}

// close connection
mysqli_close($link);
?>

Thanks!

  • 写回答

1条回答 默认 最新

  • doulei1965 2016-12-19 10:15
    关注

    Your code doesn't include the Underscore library, so _.debounce() won't be available to use. That said, you can achieve what that method does quite easily by using a setTimeout() call:

    var timeout;
    $('.search-box input[type="text"]').on("keyup input", function() {
        var term = $(this).val();
        var $resultDropdown = $(this).siblings(".result");
    
        clearTimeout(timeout);
        timeout = setTimeout(function() {
            if (term.trim().length) {
                $.get("backend-search.php", { query: term }).done(function(data) {
                    $resultDropdown.html(data);
                });
            } else {
                $resultDropdown.empty();
            }
        }, 250);
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程