select2JS Ajax选项值

时间:2015-12-15 08:35:25

标签: javascript jquery ajax

我正在用select2JS开发一个表单。

在我的第一步中,我使用了一个简单的Select2

$(this).select2();

但我想为Ajax版本更改它。

 $(this).select2({
    multiple:multival,
    ajax:
    {
        url: '/api/v2/vocabulary/'+vocabulary+'/words/list',
        headers: {'X-AUTHORIZATION-TOKEN': token},
        dataType: 'json',
        type: "POST",
        quietMillis: 100,
        data: function (params) { // Lors d'une recherche
            return {
                pattern: params.term, // search term
                page: params.page
            };
        },
        processResults: function (data, params) {
            // parse the results into the format expected by Select2
            // since we are using custom formatting functions we do not need to
            // alter the remote JSON data, except to indicate that infinite
            // scrolling can be used
            params.page = params.page || 1;

            return {
                results: data.words,
                pagination: {
                    more: (params.page * 15) < data.total
                }
            };
        },
        initSelection : function (element, callback) {
            var data = [];
            $(element.val()).each(function () {
                data.push({id: this, text: this});
            });
            callback(data);
        },
        cache: true
    },
    escapeMarkup: function (markup) {return markup; }, // let our custom formatter work
    minimumInputLength: 0,
    templateResult: function formatRepo (repo)
    {
        return repo.name;
    },
    templateSelection: function formatRepoSelection (repo)
    {
        return repo.name;
    }
});

在第一个版本中,我的Ajax返回Option的名称(当我发送表单时)。在Ajax版本中,脚本在select中创建一个新选项(但不可见),当我发送表单时,它会发送一个Id。因为在新选项的值中,它是Id而不是名称。

我使用Select2 4.0.1,我在3162'行中找到:

if (data.id) {
  option.value = data.id;
}

我尝试将data.id更改为data.name,但效果不佳。

你有什么想法吗?

0 个答案:

没有答案