我使用以下代码片段使用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,但我无法弄清楚应该在哪里保存或从我的表中删除数据.
进行一些研究我已经能够建立一个功能,它将更新上表中的记录,并且工作良好
- $('.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",data: {id: e.removed.id,action: remove},//Or you can e.removed.text
- error: function () {
- alert("error");
- }
- });
- }
- if (e.added) {
- $.ajax({
- type: "POST",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",data: {val: JSON.stringify(e.val)},//Will send all the selected values
- error: function () {
- alert("error");
- }
- });
- }
- }