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

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

表看起来像

--------------------------------- +--voucher_id--+|+--product_id--+ --------------------------------- + 123 | 566 + --------------------------------- + 156 | 566 + --------------------------------- + 123 | 426 + --------------------------------- + 156 | 516 + --------------------------------- 

我的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; } }); 

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

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

 $('.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"); } }); }); 

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

没有测试但应该工作:

 $('.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"); } }); } } 

是否有一个小提琴,您可以发布此问题的版本。

根据我的理解,以下模式是否足够?

  function dynamicSelect2(id) { $.ajax({ url: 'data-url', data: 'parameters', dataType: 'json' }).done(function () { //Create the Select2 with necessary data on the element "id" passed. }).always(function () { //Attach other events.. }); } 

可以动态创建整个select2框,并以这种方式在其上附加事件。 如果在闭包中执行此操作,则可以访问在ajax调用之前定义的变量。