Select2 ajax执行2次

时间:2015-09-01 10:37:27

标签: javascript jquery ajax jquery-select2 ui-select2

我有一个脚本从后端获取一些数据并填充select2下拉列表。问题是ajax调用总是被调用2次,它不应该是这样的。我不确定我做错了什么......任何帮助都会被贬低。

这是我的代码:

var select2Element = $('select').select2({
    theme: "classic",
    escapeMarkup: function (markup) { return markup; },
});

select2Element.on('select2:opening', function(event) {
    var clicked = $(this);

    var route = "{{ path('get_attribute_list', {'articleId': 'ARTICLEID', 'attributeGroupId': 'ATTRIBUTEGROUPID'}) }}"
    var url = route.replace("ARTICLEID", $(this).attr('data-articleId')).replace('ATTRIBUTEGROUPID', $(this).attr("data-attributeGroupId"));

    $.ajax ({
        url: url,
        dataType: 'json',
        async: false,
        type: "GET",
    }).then(function (data) {

        //@TODO get out elements already inserted

        for (var d = 0; d < data.length; d++)
        {
            var item = data[d];

            // Create the DOM option that is pre-selected by default
            var option = new Option(item.text, item.id, true, true);

            // Append it to the select
            clicked.append(option);
        }
        // Update the selected options that are displayed
        clicked.trigger('change');
    });

});

var inputResult = [];
select2Element.on('select2:select', function(e) {
    var jsonValue = {
        "articleId": $(this).attr("data-articleId"),
        "attributeGroupId": $(this).attr("data-attributeGroupId"),
        "attributeId": e.params.data.id
    }
    inputResult.push(jsonValue);

    $('#addAttributes').val(JSON.stringify(inputResult));
});

select2Element.on('select2:close', function() {
    $(this).html('');
});

1 个答案:

答案 0 :(得分:0)

似乎&#39; select2:open&#39;和&#39;选择2:开放&#39;有一个修复,但没有发布。 无论如何,在修复此问题之前,可以在此处查看更多详细信息:

https://github.com/select2/select2/issues/3503

并在此解决此问题:

https://github.com/select2/select2/commit/c5a54ed70644598529a4071672cca4a22b148806