【问题标题】:JQuery-Select2 - Manipulate the sended http-post data to send the text not the IDsJQuery-Select2 - 操作发送的 http-post 数据以发送文本而不是 ID
【发布时间】:2014-08-04 11:27:06
【问题描述】:

有一段时间我在 Bootstrap 3 中使用了 tagsinput,它工作正常。现在我改成了 select2,它非常简单而且非常好。我只有两个小问题,希望你能帮助我——我不太确定如何处理 javascript。

先决条件:select2 正在工作,使用 ajax 和 json-response。 select2 用于标签输入。

1. 当用户发送表单时,他输入的新词以这种方式发送,他从 ajax-response 中选择的词通过其 id 发送。我需要的是,所有输入和选择的单词都作为单词(没有 ID)发送。

我需要在脚本中的什么地方进行更改? 我试过了:

results: function (data) {
    return {
        results: data
    };
}
to results: function (data) {
    return {
        results: data.text
    };
}

但这破坏了搜索功能。

2. 第二个问题可能相同。当用户刷新表单时,他输入的新词会显示出来,但他从 ajax-request 中选择的词只显示他们的 ID。

$(document).ready(function () {
    $('#keywords').select2({
        tags: true,
        tokenSeparators: ["\n"],
        createSearchChoice: function (term) {
            return {
                id: term,
                text: term
            };
        },
        ajax: {
            url: "/slipbox/entities/jsonKeywords",
            dataType: 'json',
            data: function (term) {
                return {
                    q: term
                };
            },
            results: function (data) {
                return {
                    results: data
                };
            }
        },
        initSelection: function (element, callback) {
            var data = [];

            function splitVal(string, separator) {
                var val, i, l;
                if (string === null || string.length < 1) return [];
                val = string.split(separator);
                for (i = 0, l = val.length; i < l; i = i + 1) val[i] = $.trim(val[i]);
                return val;
            }
            $(splitVal(element.val(), ",")).each(function () {
                data.push({
                    id: this,
                    text: this
                });
            });
            callback(data);
        }
    });
});

非常感谢您,并致以最良好的祝愿 阿尔约沙

【问题讨论】:

    标签: javascript jquery forms http-post jquery-select2


    【解决方案1】:

    将此代码添加到我们的 select2 中:

    id: function(object) {
            return object.text;
        }
    

    我用的是3.5.2版本

    【讨论】:

      猜你喜欢
      • 2015-06-02
      • 2017-08-09
      • 1970-01-01
      • 2014-06-17
      • 2012-02-05
      • 1970-01-01
      • 1970-01-01
      • 2017-03-25
      • 1970-01-01
      相关资源
      最近更新 更多