首頁  >  文章  >  後端開發  >  PHP實作搜尋框自動補全功能的方法

PHP實作搜尋框自動補全功能的方法

PHPz
PHPz原創
2024-03-07 08:00:121115瀏覽

PHP實作搜尋框自動補全功能的方法

搜尋框自動補全是常見的網頁功能,能夠提升使用者體驗並簡化搜尋流程。在PHP中實作搜尋框自動補全功能可以透過Ajax非同步請求來實現。以下將介紹具體的實作方法,包括前端程式碼和後端程式碼範例。

前端程式碼範例:

<!-- index.html -->

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>搜索框自动补全</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>

<h1>搜索框自动补全示例</h1>

<input type="text" id="search" placeholder="输入关键词搜索">

<div id="suggestions">
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="script.js"></script>
</body>
</html>
/* styles.css */

#suggestions {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    border: 1px solid #ccc;
    max-width: 300px;
}
// script.js

$(document).ready(function(){
    $('#search').keyup(function(){
        var keyword = $(this).val();
        if(keyword != ''){
            $.ajax({
                url: 'autocomplete.php',
                type: 'post',
                data: {keyword: keyword},
                success: function(response){
                    $('#suggestions').html(response);
                    $('#suggestions').show();
                }
            });
        } else {
            $('#suggestions').hide();
        }
    });
});

後端PHP程式碼範例:

// autocomplete.php

<?php

$keywords = ['PHP', 'JavaScript', 'Python', 'HTML', 'CSS', 'MySQL', 'AJAX' ]; // 模拟关键词数据源

if(isset($_POST['keyword'])){
    $input = $_POST['keyword'];
    $suggestions = '';
    
    foreach($keywords as $word){
        if(stripos($word,$input) !== false){
            $suggestions .= '<div>' . $word . '</div>';
        }
    }
    
    echo $suggestions;
}

?>

在上面的程式碼範例中,前端使用jQuery實作了搜尋框關鍵字輸入時發起Ajax請求,後端PHP根據接收的關鍵字資料進行模糊匹配,並返回匹配的關鍵字列表,最終展示在頁面上,實現了搜尋框自動補全的功能。使用者在輸入搜尋關鍵字的過程中,會即時出現符合的關鍵字提示,提升了搜尋的準確性與效率。

透過以上所提供的PHP實作搜尋框自動補全功能的方法和程式碼範例,希望能夠協助您實現此功能,提升網站搜尋的使用者體驗。

以上是PHP實作搜尋框自動補全功能的方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn