javascript - Select2:使用 ajax 创建标签
问题描述
我正在使用 select2 库。
我的 select2 元素可以通过 ajax 在数据库中搜索每个标签,并且效果很好。
我的问题是,我希望用户也能够创建一个新标签。查看他们的文档,我应该使用该createTag
选项;但是,只要我单击元素并在每次按键时都会触发。
任何人都可以就我如何实现目标提供任何指导吗?
到目前为止,这是我的代码
I am using ajax top search for tags but I would also like to create new tags to the database. I have tried doing this via createTag but this seems to be firing as soon as I click in the HTML element and on each key press.
Here is my code:
$('.tags').select2({
tags: true,
placeholder: "These tags will apply to all lines",
tokenSeparators: [','],
ajax: {
url: '/api/tags/find',
dataType: 'json',
data: function (params) {
return {
q: $.trim(params.term)
};
},
processResults: function (data) {
return {
results: data
}
},
cache: true,
},
createTag: function(params) {
alert('tag created') // This is were I would put my ajax POST.
}
});
解决方案
再次阅读文档后,我可以看到我应该一直在使用事件https://select2.org/programmatic-control/events
我使用了createTag
分配newTag: true
给新创建的标签的选项,并使用了select2:selected
检查是否选择了新标签的事件,如果是,则向服务器发送 ajax 请求以创建该标签。
$('.tags').select2({
tags: true,
placeholder: "These tags will apply to all lines",
minimumInputLength: 3,
tokenSeparators: [','],
ajax: {
url: '/api/tags/find',
dataType: 'json',
data: function (params) {
return {
q: $.trim(params.term)
};
},
processResults: function (data) {
return {
results: data
}
},
// cache: true,
},
createTag: function(params) {
let term = $.trim(params.term);
if (term.length < 3)
{
return null
}
return {
id: term,
text: term,
newTag: true,
}
},
});
$('.tags').on('select2:select', function (e) {
let tag = e.params.data;
if (tag.newTag === true)
{
axios.post('/api/newtag', {
name: tag.text,
type: 'default',
})
}
});
推荐阅读
- sql - 将计算列添加到表中,通过关联的 id 计数来自另一个表的记录
- sql - 在 MAX 函数中嵌套 IIF 函数
- reactjs - React-Select 和 React-Flow 重叠
- reactjs - 如何在值更改时设置 redux 表单字段的可见性?
- php - 按用户角色从特定管理员 url 重定向到另一个 url
- android - 如何从命令行设置 android 仪器测试的 vm heapsize
- python - 用python中的输入制作一个列表
- spring-boot - SpringBoot 测试:ReactiveMongoRepository 的 NoSuchBeanDefinitionException
- c# - CSScript 重新编译?
- python - 具有多个参数的 __str__ 函数的继承错误