gpt4 book ai didi

javascript - 选择 2 : Creating tags with ajax

转载 作者:行者123 更新时间:2023-12-05 03:57:43 27 4
gpt4 key购买 nike

我正在使用 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',
})
}
});

关于javascript - 选择 2 : Creating tags with ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58397929/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com