首页 > 解决方案 > 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. 
              }
          });

标签: javascriptjquery-select2jquery-select2-4

解决方案


再次阅读文档后,我可以看到我应该一直在使用事件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',
                  })
              }
          });


推荐阅读