如何在select2 new/remove标记事件上触发新的ajax?

fef*_*efe 7 ajax jquery twitter-bootstrap jquery-select2

我使用以下代码片段与ajax远程添加一个新的select2标签,我想在新标签/删除标签事件上注册或删除我的多对多表的一些记录

表看起来像

---------------------------------
+--voucher_id--+|+--product_id--+
---------------------------------
+     123       |   566         +
---------------------------------
+     156       |   566         +
---------------------------------
+     123       |   426         +
---------------------------------
+     156       |   516         +
---------------------------------
Run Code Online (Sandbox Code Playgroud)

我的Javascript

$(".e6").select2({
    tags: true,
    placeholder: 'placeholder',
    minimumInputLength: 1,

    ajax: {
        url: 'searchProducts',
        dataType: 'json',
        data: function(term) {
            return {q: term};
        },
        results: function(data) {
            return {results: data};
        }
    },
    createSearchChoice: function(term, data) {
        if ($(data).filter(function() {
            return this.computername.localeCompare(term) === 0;
        }).length === 0) {
            return {id: term, name: term};
        }
    },
    formatResult: function(item, page) {
        return item.computername;
    },
    formatSelection: function(item, page) {
        return item.computername;
    }
});
Run Code Online (Sandbox Code Playgroud)

在返回的json中我也有一个产品ID,我正在搜索在select2事件上触发新的ajax的方法,但我无法弄清楚应该在哪里保存或从我的表中删除数据.

进行一些研究我已经能够建立一个功能,可以更新上表中的记录,并且工作良好

$('.e6').on("change", function(e){                           
    console.log(ids);
    console.log(gs);
    $.ajax({
        type: "POST",
        url: '/admin/?controller=vouchers&action=updateRelatedProducts',
        data: {ids: ids, gs:gs},
        error: function () {
            alert("error");
        }
    });                   
});
Run Code Online (Sandbox Code Playgroud)

但是我在使用初始现有标签填充输入字段时遇到问题

Kal*_*zem 5

没有测试但应该工作:

$('.e6').on("change", function(e){
    if (e.removed) {
        $.ajax({
            type: "POST",
            url: '/admin/?controller=vouchers&action=updateRelatedProducts',
            data: {id: e.removed.id, action: remove},    //Or you can e.removed.text
            error: function () {
                alert("error");
            }
        });
    }
    if (e.added) {
        $.ajax({
            type: "POST",
            url: '/admin/?controller=vouchers&action=updateRelatedProducts',
            data: {id: e.added.id, action: add},    //Or you can e.added.text
            error: function () {
                alert("error");
            }
        });
    }

    //OR you can play with val data instead
    if (e.val) {
        $.ajax({
            type: "POST",
            url: '/admin/?controller=vouchers&action=updateRelatedProducts',
            data: {val: JSON.stringify(e.val)},    //Will send all the selected values
            error: function () {
                alert("error");
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)