How to use Layui to implement automatic search function
Introduction:
Layui is a lightweight front-end development framework that is easy to use and has rich features. Components and modules, including forms, pop-up windows, navigation, menus, etc. The autocomplete component can help us implement intelligent prompts when searching and provide a better user experience. This article will introduce in detail how to use Layui's autocomplete component to implement the search function, and provide specific code examples.
Step 1: Introduce Layui and jQuery
First, introduce the script files of Layui and jQuery in HTML. You can download the latest version of Layui from the Layui official website (https://www.layui.com/) and extract it into the project. Then, introduce the following two script files into HTML:
Step 2: Create a search box and result container
Create an input box and a container for displaying search results in HTML. For example:
Among them,searchInput
is the id of the input box, andsearchResult
is the id of the result container.
Step 3: Write JavaScript code
Call Layui’s autocomplete component in JavaScript to implement the search function. First, introduce the auto-complete module through thelayui.use()
method and initialize it:
layui.use('autocomplete', function() { var autocomplete = layui.autocomplete; autocomplete.render({ elem: '#searchInput', // 输入框元素选择器 url: 'path/to/searchApi', // 搜索接口地址 method: 'post', // 请求方式,默认为'get' onselect: function(data) { // 选择某个提示项后的回调函数 // 在此处可以进行相关操作,如打开搜索结果页面等 console.log(data); } }); });
Among them, theelem
parameter specifies the selector of the input box, ## The #urlparameter specifies the address of the search interface. These parameters can be modified according to actual conditions.
onselectcallback function, you can perform related operations according to your own needs. For example, you can obtain the data of the prompt item selected by the user through the
dataparameter, and open the corresponding search results page.
Write an interface to process search requests in the background and return prompt item data that matches the user's input. The sample code is as follows (taking PHP as an example):
1, 'value' => 'Apple', 'group' => 'Fruit'), array('id' => 2, 'value' => 'Banana', 'group' => 'Fruit'), array('id' => 3, 'value' => 'Carrot', 'group' => 'Vegetable'), // ... ); // 将查询结果以JSON格式返回给前端 header('Content-Type: application/json'); echo json_encode($result); ?>
Through the above steps, we can use Layui's auto-complete component to implement the search function and provide intelligent prompts. In actual projects, it can be customized and expanded according to needs to improve user experience.
The above is the detailed content of How to use Layui to implement automatic search function. For more information, please follow other related articles on the PHP Chinese website!