Bootstrap教程

Bootstrap 自动完成搜索

Bootstrap 自动完成搜索

在本节中,我们将使用Bootstrap Typeahead JS进行动态自动完成搜索。提前输入也可以称为自动建议或自动完成。它是一种用于语言预测的工具。许多搜索界面都使用此工具。当客户在搜索栏中键入内容时,他们将获得一些建议。当用户在搜索栏中键入内容时,Typeahead会提供预测。
现代的Web表单具有非常流行的搜索工具,即typeahead输入字段。 Typeahead通常用于改善用户体验。该工具在用户搜索内容或填写表单时查看用户输入的文本。基于这些内容,Typeahead向用户提供提示和可能选择的列表。搜索可以是任何类型。当我们使用Typeahead时,我们将减少潜在的错误,并且还可以节省时间,因为在使用Typeahead时,用户的拼写错误将更少。
首先,我们将创建 html 布局。我们将添加 JQuery 和在Ajax.html文件中提前输入Bootstrap 。如果尝试在输入框上写一些内容,则可以进行动态自动完成搜索。通过使用Ajax请求是可能的。因此,将首先使用以下代码创建ajax.html文件:
ajax.html:
<html lang="en">
<head>
    <title> Example of Bootstrap Typeahead with Ajax </title>  
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.1/bootstrap3-typeahead.min.js"></script>  
</head>
<body>
<div class="row">
    <div class="col-md-12 text-center">
        <br/>
        <h1> Example of Dynamic Autocomplete search using Bootstrap Typeahead JS</h1>   
            <input class="typeahead form-control" style="margin:0px auto;width:300px;" type="text">
    </div>
</div>
<script type="text/javascript">
    $('input.typeahead').typeahead({
        source:  function (query, process) {
        return $.get('/ajaxpro.php', { query: query }, function (data) {
                console.log(data);
                data = $.parseJSON(data);
                return process(data);
            });
        }
    });
</script>
</body>
</html>
现在我们的示例需要 JSON 数据。我们将通过创建一个新页面并根据Ajax请求获得此功能。因此,在下面的示例中,我们将再创建一页ajaxpro.php文件。之后,我们将添加以下代码:
ajaxpro.php:
<?php
    
    define (DB_USER, "root");
    define (DB_PASSWORD, "root");
    define (DB_DATABASE, "learn");
    define (DB_HOST, "localhost");
    $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
    $sql = "SELECT items.title FROM items 
            WHERE title LIKE '%".$_GET['query']."%'
            LIMIT 10"; 
    $result = $mysqli->query($sql);
    
    s$json = [];
    while($row = $result->fetch_assoc()){
         $json[] = $row['title'];
    }
    echo json_encode($json);
我们的以上代码已准备就绪,可以运行。运行此代码时,将获得以下输出:
使用Bootstrap Typeahead JS示例进行动态自动完成搜索
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4