切换开关触发Ajax POST请求失效问题求助
问题:Toggle开关Ajax请求功能失效
需求:实现Toggle开关功能,勾选/取消勾选时分别发起对应Ajax POST请求,请求完成后禁用开关。
原始代码
HTML部分
<form method="POST"> <table class="table-hover mb-0 wd-100p"> <tbody class="tx-12"> <tr> <td>Betting</td> <td class="tx-right"> <label class="switch"> <input type="checkbox" class="primary" id="toggle_1" data-toggle="toggle" data-off="Disabled" data-on="Enabled" /> <span class="slider round"></span> </label> </td> </tr> </tbody> </table> </form>
JavaScript部分
function callA() { $('#toggle_1').change(function(){ if ($(this).is(':checked')) { function Execute() { $.ajax({ type: "POST", url: "file1.php", data: {}, success: function(response) { $("#display_response").html(response.msg); $("#toggle_1").attr("disabled", true); }, error: function() { alert("error"); }, }); } }; if ($(this).is(':checked') == false) { function Execute() { $.ajax({ type: "POST", url: "file2.php", data: {}, success: function(response) { $("#display_response").html(response.msg); $("#toggle_1").attr("disabled", true); }, error: function() { alert("error"); }, }); } }; }); } $(document).ready(function() { callA(); });
问题分析与修复
原始代码核心问题:
change事件回调里定义了Execute函数但从未调用,导致Ajax请求完全没触发- 重复定义
Execute函数,属于冗余且不符合语法规范 - 开关状态判断逻辑冗余,无需两次调用
is(':checked') - 设置禁用状态用
attr不如prop可靠(jQuery针对布尔属性推荐用prop)
修复后的完整代码
<form method="POST"> <table class="table-hover mb-0 wd-100p"> <tbody class="tx-12"> <tr> <td>Betting</td> <td class="tx-right"> <label class="switch"> <input type="checkbox" class="primary" id="toggle_1" data-toggle="toggle" data-off="Disabled" data-on="Enabled" /> <span class="slider round"></span> </label> </td> </tr> </tbody> </table> </form> <div id="display_response"></div> <script> $(document).ready(function() { $('#toggle_1').change(function(){ const $toggle = $(this); // 根据开关状态确定请求地址 const requestUrl = $toggle.is(':checked') ? 'file1.php' : 'file2.php'; // 发起Ajax请求 $.ajax({ type: "POST", url: requestUrl, data: {}, success: function(response) { $("#display_response").html(response.msg); // 禁用开关 $toggle.prop("disabled", true); }, error: function() { alert("请求失败"); }, }); }); }); </script>
修复细节说明
- 移除冗余的
callA函数,直接在document.ready中绑定事件,简化结构 - 用变量缓存
$(this),避免重复DOM查询 - 三元运算符简化请求地址判断逻辑,减少冗余代码
- 直接执行Ajax请求,去掉无用的
Execute函数定义 - 改用
prop("disabled", true)设置禁用状态,符合jQuery最佳实践 - 补充
#display_response元素的HTML(若页面原本没有需添加)
内容的提问来源于stack exchange,提问作者Frank
相关产品推荐
相关产品推荐

