tagsinput和typeahead生成标签

本文介绍如何使用Bootstrap Tagsinput插件结合Ajax实现标签自动填充功能。通过具体示例代码展示了前端设置及后端SpringBoot控制器的实现方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

bootstrap-tagsinput是一款插件,用于页面tag标签生成。

它支持自己手动输入,同时也能在ajax基础上智能填充输入框内容。

一般的功能,官网上有介绍。不过对于自动填充这块,需要详细说明一下。


效果图

这里写图片描述

require

bootstrap-tagsinput-angular.js

bootstrap-tagsinput.js

bootstrap-tagsinput.css

bootstrap3-typeahead.min.js(注意,这里需要的这个typeahead和官网上的有所区别。官网的存在问题!)

html

<div class="col-md-8 col-md-offset-2">
        <input id="tags" type="text" class="form-control" placeholder="请输入标签" data-role="tagsinput"/>
</div>

<script th:inline="javascript">

    $('#tags').tagsinput({
        maxTags: 5,

        //表示ajax接收后数据对应格式
        itemValue: 'id',
        itemText: 'name',

        typeahead: {
            displayKey: 'name',
            source: function(query) {
                return $.get('/tag/list', {query: query});
            },
            //清除input上多出来的一条无效数据 
            afterSelect: function() {
                this.$element[0].value = '';
            }
        },
        freeInput: true
    });
</script>

java

这里用的是springboot

@Controller
@RequestMapping("/tag")
public class TagController {

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public @ResponseBody List<Tag> getTagsList(@RequestParam String query) {
        return new TagServiceImpl().getTagsByName(query);
    }
}

数据格式

返回的格式如下,前台只用到了id和name。

也可以这么返回:[‘java’, ‘php’, ‘c++’]。只要封装成一个List即可。

[
  {
    "id": "001",
    "createdId": null,
    "createdName": null,
    "createdTime": null,
    "name": "java"
  },
  {
    "id": "002",
    "createdId": null,
    "createdName": null,
    "createdTime": null,
    "name": "php"
  },
  {
    "id": "003",
    "createdId": null,
    "createdName": null,
    "createdTime": null,
    "name": "c++"
  }
]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值