You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据Ajax结果将Toggle切换回之前的状态?

解决Bootstrap Toggle在Ajax失败时恢复状态的问题

你的问题根源在于使用了Bootstrap Toggle插件,它会把原生checkbox包装为自定义UI组件,直接修改原生checkbox的checked属性无法同步到插件渲染的开关UI上,必须使用插件提供的API来操作状态。另外你之前的选择器也有误,错误地选中了form元素而非checkbox本身。

修正步骤:

  1. 修正选择器:选中对应的checkbox元素(而非form),你的checkbox的id就是sid的值,所以用$('#' + sid)来定位。
  2. 使用Bootstrap Toggle API:调用bootstrapToggle('on')或bootstrapToggle('off')来切换开关状态,而非直接修改prop('checked')。
  3. 完善错误回调:Ajax请求失败时也要恢复状态,避免用户操作无反馈。

修改后的完整代码:

jQuery部分:

function onToggle() {
    var page = $(".statusForDetail").attr('page');
    // 直接绑定到toggle-class类,无需遍历hidden元素,更简洁
    $('.toggle-class').change(function () {
        let id = $(this).data('id');
        let status_val = this.checked ? 1 : 0;
        updateStatus(status_val, id, page, id);
    });
}

function updateStatus(status_val, id, page, sid) {
    $.ajax({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        type: "POST",
        url: "/admin/" + page,
        data: {status: status_val, id: id},
        success: function (result) {
            if (result[0] == "Success!") {
                $("#updatedAt").fadeIn(0).html("<font color='green' font size='2px'> : " + result[0] + result[1] + "</font>").fadeOut(1500);
            } else {
                $("#updatedAt").fadeIn(0).html("<font color='red'>" + result[0] + result[1] + "</font>").fadeOut(1500);
                // 用Bootstrap Toggle API恢复状态
                if (status_val == 1) {
                    $('#' + sid).bootstrapToggle('off');
                } else {
                    $('#' + sid).bootstrapToggle('on');
                }
            }
        },
        error: function () {
            $("#updatedAt").fadeIn(0).html("<font color='red'>请求失败,请重试</font>").fadeOut(1500);
            // 请求失败时同样恢复状态
            if (status_val == 1) {
                $('#' + sid).bootstrapToggle('off');
            } else {
                $('#' + sid).bootstrapToggle('on');
            }
        }
    });
}

关键说明:

  • Bootstrap Toggle插件会替换原生checkbox的视觉表现,所以必须通过它的API来修改状态,才能让UI同步更新。
  • 简化了事件绑定逻辑,直接通过.toggle-class类绑定change事件,避免了不必要的DOM遍历,提升代码效率。

内容的提问来源于stack exchange,提问作者Orkhan Orkhan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 15:19:21