手搭手Ajax实现搜索地址自动补全功能

举报
QGS 发表于 2023/11/05 23:05:03 2023/11/05
【摘要】 手搭手Ajax实现搜索地址自动补全功能

输入单词后,自动提示出要搜索的信息,点击某个内容后,自动补全至搜索框。

比如:

如何实现搜索自动补全功能

  1. 键盘事件:keyup按键弹起事件
  2. 发送ajax请求,请求中提交用户输入的搜索内容,后端接收内容后,模糊查询,返回结果list<*>
  3. 查询结果封装json格式的字符串后,将json字符串响应到前端,
  4. 前端接收,动态展示


环境介绍

技术栈

springboot+mybatis-plus+mysql

软件

版本

mysql

8

IDEA

IntelliJ IDEA 2022.2.1

JDK

1.8

Spring Boot

2.7.13

mybatis-plus

3.5.3.2

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.15</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>ajaxDemo01</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>ajaxDemo01</name>
    <description>ajaxDemo01</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>2.0.32</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.3.2</version>
        </dependency>
        <dependency>
            <groupId>p6spy</groupId>
            <artifactId>p6spy</artifactId>
            <version>3.9.1</version>
        </dependency>
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.15</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
            <version>3.5.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.24</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

application.yml配置文件

spring:
  datasource:
#    username: root
#    password: 111111
#    url: jdbc:p6spy:mysql://xxx.xxx.xxx.136:3306/sys?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8
#    driver-class-name: com.p6spy.engine.spy.P6SpyDriver
    dynamic:
      primary: sys #设置默认的数据源或者数据源组,默认值即为master
      strict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
      datasource:
        sys:
          username: root
          password: 111111
          url: jdbc:p6spy:mysql://xxx.xxx.xxx.136:3306/sys?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8
          driver-class-name: com.p6spy.engine.spy.P6SpyDriver
#          driver-class-name: com.mysql.jdbc.Driver
        wms:
          url: jdbc:p6spy:mysql://xxx.xxx.xxx.136:3306/Wms?useUnicode=true&characterEncoding=UTF-8
          username: root
          password: 111111
          driver-class-name: com.p6spy.engine.spy.P6SpyDriver
#          driver-class-name: com.mysql.jdbc.Driver
        sys2:
          username: root
          password: 111111
          url: jdbc:p6spy:mysql://127.0.0.1:3306/sys?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8
          driver-class-name: com.p6spy.engine.spy.P6SpyDriver

server:
  port: 8083

mybatis-plus:
  configuration:
    #输出日志
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    #配置映射规则
    map-underscore-to-camel-case: true #表示支持下划线到驼蜂的映射
    #隐藏mybatis图标
  global-config:
    banner: false
    db-config:
      logic-delete-field: status
      logic-not-delete-value: 1
      logic-delete-value: 0
#
#mybatis:
#  mapper-locations=classpath: com/example/dao/*.xml

数据库表

前端页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>实现搜索地址自动补全功能</title>
    <style>
        .userInput{
            width: 300px;
            height: 25px;
            font-size: 20px;
            padding-left: 8px;
        }
        .mouse_color{
            background-color: antiquewhite;
        }
        .showData{
            width: 383px;
            font-size: 20px;
            border: 1px solid lightgray;
        /*    隐藏*/
            display: none;

        }
        .showData p {
            margin-top: 0px;
        }
        /*移动到上面改变背景颜色,并且变成小手*/
        .showData p:hover {
            cursor: pointer;
            background-color: antiquewhite;
            border: 1px  solid lightgray ;
        }

    </style>
</head>
<body>
<script type="text/javascript" src="../js/jquery-3.4.1.js"></script>
搜索地址: <input type="text" class="userInput" id="InputEnter">
<div class="showData" id="addressData">
<!--    <p>广州市增城区东湖路增城东湖公园</p>
        <p>广州市增城区广汕公路江山时代花园</p>
        <p>广州市花都区王子山路</p>
        <p>广东省广州市从化江埔街锦二村</p>
        <p>广东省深圳市莲花山</p>
        <p>广东省深圳市罗湖口岸</p>
        <p>广东省深圳市深圳机场</p>
        <p>广州市增城区东湖路增城东湖公园</p>
        <p>广西壮族自治区桂林市象山区</p>
        <p>广西壮族自治区南宁市上林县</p>
        <p>广西壮族自治区南宁市横县</p>
        <p>广西壮族自治区南宁市青秀区</p>
        <p>海南省三亚市南山文化旅游区</p>
        <p>海南省海口市美兰区</p>
        <p>海南省藏族自治州</p>
        <p>海南省三亚市崖州区</p>-->
</div>

<script type="text/javascript">
    window.onload = function () {
        document.getElementById("InputEnter").onkeyup = function () {
            // console.log(this.value)
            if (this.value!=null &&  this.value!=""){
                document.getElementById("addressData").style.display= "none";
            }
                $.ajax({
                    url: "/"+this.value+"/Address",
                    type: "GET",
                    dataType: "JSON",
                    success: function (json){
                        //清空原来的数据
                        $("#addressData").empty();
                        let list = json;
                        let html="";
                        for (let i = 0; i < list.length; i++){
                            console.log(list[i].address)
                            html +="<p onclick='SetInputValue(\""+list[i].address+"\")'>"+list[i].address+"</p>"
                        }
                        document.getElementById("addressData").innerHTML = html;
                        document.getElementById("addressData").style.display= "block";
                    },
                    error: function (xhr){
                        document.getElementById("addressData").innerHTML = "没有搜索到该地址";
                    }
                });

            
        }
    }
    //被点击后将内容设置到搜索框
    function SetInputValue(address) {
        document.getElementById("InputEnter").value = address
        document.getElementById("addressData").style.display= "none"
    }
</script>
</body>
</html>


后端实现

实体类

@TableName(value ="t_address")
@Data
public class TAddress implements Serializable {
    /**
     * 
     */
    @TableId(type = IdType.AUTO)
    private Integer id;

    /**
     * 
     */
    private String address;

    @TableField(exist = false)
    private static final long serialVersionUID = 1L;
}

mapper(dao层)

@Mapper
public interface TAddressMapper extends BaseMapper<TAddress> {
    List<TAddress> getByAddresses(@Param("Data") String data);
}

service

public interface TAddressService extends IService<TAddress> {
    List<TAddress> getAddresses(String data);
}

serviceimpl

@Service
@DS("sys2")
public class TAddressServiceImpl extends ServiceImpl<TAddressMapper, TAddress>
    implements TAddressService{

    @Autowired
    private TAddressMapper tAddressMapper;

    @Override
    public List<TAddress> getAddresses(String data) {
        return tAddressMapper.getByAddresses(data);
    }
}

controller

@Autowired
    private TAddressServiceImpl tAddressService;

@RequestMapping("/{Data}/Address")
@ResponseBody
public List<TAddress> Address(@PathVariable("Data") String data) {

    List<TAddress> allProvince = tAddressService.getAddresses(data);
    return allProvince;
}


测试类

@Autowired
private TAddressServiceImpl tAddressService;


@Test
void addressTest(){
    List<TAddress> address = tAddressService.list();
    for (TAddress tAddress : address) {
        System.out.println(tAddress.toString());
    }
}


效果









【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。