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

前端之家收集整理的这篇文章主要介绍了jquery – 如何在select2 new/remove标记事件上触发新的ajax?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用以下代码片段使用ajax远程添加新的 select2标记,我想在新标记/删除标记事件上注册删除我的多对多表的一些记录

表看起来像

  1. ---------------------------------
  2. +--voucher_id--+|+--product_id--+
  3. ---------------------------------
  4. + 123 | 566 +
  5. ---------------------------------
  6. + 156 | 566 +
  7. ---------------------------------
  8. + 123 | 426 +
  9. ---------------------------------
  10. + 156 | 516 +
  11. ---------------------------------

我的Javascript

  1. $(".e6").select2({
  2. tags: true,placeholder: 'placeholder',minimumInputLength: 1,ajax: {
  3. url: 'searchProducts',dataType: 'json',data: function(term) {
  4. return {q: term};
  5. },results: function(data) {
  6. return {results: data};
  7. }
  8. },createSearchChoice: function(term,data) {
  9. if ($(data).filter(function() {
  10. return this.computername.localeCompare(term) === 0;
  11. }).length === 0) {
  12. return {id: term,name: term};
  13. }
  14. },formatResult: function(item,page) {
  15. return item.computername;
  16. },formatSelection: function(item,page) {
  17. return item.computername;
  18. }
  19. });

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

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

  1. $('.e6').on("change",function(e){
  2. console.log(ids);
  3. console.log(gs);
  4. $.ajax({
  5. type: "POST",url: '/admin/?controller=vouchers&action=updateRelatedProducts',data: {ids: ids,gs:gs},error: function () {
  6. alert("error");
  7. }
  8. });
  9. });

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

解决方法

没有测试但应该工作:
  1. $('.e6').on("change",function(e){
  2. if (e.removed) {
  3. $.ajax({
  4. type: "POST",data: {id: e.removed.id,action: remove},//Or you can e.removed.text
  5. error: function () {
  6. alert("error");
  7. }
  8. });
  9. }
  10. if (e.added) {
  11. $.ajax({
  12. type: "POST",data: {id: e.added.id,action: add},//Or you can e.added.text
  13. error: function () {
  14. alert("error");
  15. }
  16. });
  17. }
  18.  
  19. //OR you can play with val data instead
  20. if (e.val) {
  21. $.ajax({
  22. type: "POST",data: {val: JSON.stringify(e.val)},//Will send all the selected values
  23. error: function () {
  24. alert("error");
  25. }
  26. });
  27. }
  28. }

猜你在找的jQuery相关文章