jQuery   发布时间:2022-04-19  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了jquery – 如何在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,但我无法弄清楚应该在哪里保存或从我的表中删除数据.

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

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

大佬总结

以上是大佬教程为你收集整理的jquery – 如何在select2 new/remove标记事件上触发新的ajax?全部内容,希望文章能够帮你解决jquery – 如何在select2 new/remove标记事件上触发新的ajax?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。