【问题标题】:Get id from database when create tag in Select2在 Select2 中创建标签时从数据库中获取 id
【发布时间】:2016-08-26 14:56:56
【问题描述】:

我有一个 select2 标记控件。当标签不存在时,用户可以创建标签。此标签保存在数据库中,但问题是我不知道如何设置为 ajax 成功返回的标签 id。

$tags.select2({
    placeholder: '- Select -',
    tags: true,
    tokenSeparators: [',', ' '],
    createTag: function (params) {
        if (params.term.trim() === '') {
            return null;
        }
        return {
            id: '', //How to get id here???
            text: params.term.toLowerCase(),
            newTag: true // add additional parameters
        }
    },
    //Ajax to get tags here ommited
});

$tags.on('select2:select', function (e) {
    if (e.params.data.newTag) {
        $.ajax({
            url: urlAddTag,
            type: 'POST',
            dataType: "json",
            data: { tag: e.params.data.text.toLowerCase() },
            success: function (response) {
                 e.params.data.id = response.id;
            },
            error: function (xhr, ajaxOptions, thrownError) {
                var msg = JSON.parse(xhr.responseText);
            }
        });
    }
});

在 ajax 响应中,我正在设置标签存储在数据库中的 id,但我不知道如何传递给“createTag”函数。

【问题讨论】:

    标签: javascript ajax select2


    【解决方案1】:

    我有一些类似的问题,我通过以下方式解决了,我不希望这能 100% 适应你的情况,但它可能会给你一个想法。

    我的流程是这样工作的:

    • 在 createTag 中,我只是创建了一些随机 id,它们将被发送到 API
    • API 将忽略此 ID,并使用 来自 select2 组件的文本
    • API 在响应中返回新的 ID(和文本)
    • 在回调中,您使用新 ID 更新 select2 上的标签 刚刚得到

    例如在你的情况下:

    createTag: function(params) {
      if (params.term.trim() === '') {
          return null;
      }
      return {
          id: 'new_attribute',
          isNew: true,
          text: params.term
      };
    }
    

    在服务器回调中,我搜索控件中的标签并使用从服务器获取的 ID 更新其 ID:

    $('<option/>').val(response.id).html(response.text).appendTo($tags); //create a new option with id + text returned by the server
    var tags = $tags.val(); //get current values
    var index = tags.indexOf('new_attribute'); //look for new_attribute
    if (index !== -1) {
        tags[index] = response.id; //replace 'new_attribute' with id got from the server
    }
    $tags.val(tags).trigger('change'); //update select2
    

    【讨论】:

    • 我认为必须有一种不同的方法来通过回调来完成此任务,但与此同时,我将使用这个 hack,谢谢达里奥
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-23
    • 1970-01-01
    • 2022-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多