在jQuery的.done()函数处理数据时,如何移除beforeSend()函数?
jQuery AJAX提交后无法恢复按钮状态与加载提示的问题解决
我正在学习jQuery,公司项目里广泛用到它。现在遇到一个AJAX提交表单的问题:提交时通过beforeSend能成功禁用提交按钮、显示加载提示,但AJAX的.done()回调执行后,无法恢复按钮可用状态和隐藏加载提示。
原代码:
<!-- post form data --> <script> $(document).ready(function() { $(".startup_form").on("submit", function(event) { event.preventDefault(); let formData = $(this).serialize(); $.ajax({ type: "POST", url: "bot/company_crawler.php", data: formData, dataType: "json", encode: true, beforeSend: function() { $("#submitBtn").attr('disabled','disabled'); $("#loading").removeClass('hide'); $("#loading").addClass('show'); } }).done(function(data) { $("#submitBtn").removeAttr('disabled'); $("#loading").addClass('hide'); $("#loading").removeClass('show'); console.log(data); }); }); }); </script> <!-- ./post form data -->
解决方法:
添加请求失败后的状态恢复逻辑
目前代码只在请求成功时恢复状态,若请求失败(网络异常、后端报错等),.done()不会触发,按钮会一直处于禁用状态。建议用.always()回调统一处理状态恢复,它无论请求成功或失败都会执行:.done(function(data) { console.log(data); }) .fail(function(xhr, status, error) { console.error("请求失败:", error); // 可在此添加前端错误提示 }) .always(function() { $("#submitBtn").prop('disabled', false); $("#loading").addClass('hide').removeClass('show'); });改用
.prop()处理按钮禁用状态
jQuery中操作表单元素的禁用状态,.prop()比.attr()更可靠,因为disabled是元素的原生属性(property)而非HTML标签属性(attribute):// beforeSend中设置禁用 $("#submitBtn").prop('disabled', true); // always中恢复可用 $("#submitBtn").prop('disabled', false);确认DOM选择器的正确性
检查页面中#submitBtn和#loading的ID是否唯一且拼写正确,可在回调函数中添加console.log($("#submitBtn")),验证是否能正确选中目标元素。
修改后的完整代码:
<!-- post form data --> <script> $(document).ready(function() { $(".startup_form").on("submit", function(event) { event.preventDefault(); let formData = $(this).serialize(); $.ajax({ type: "POST", url: "bot/company_crawler.php", data: formData, dataType: "json", encode: true, beforeSend: function() { $("#submitBtn").prop('disabled', true); $("#loading").removeClass('hide').addClass('show'); } }).done(function(data) { console.log(data); }).fail(function(xhr, status, error) { console.error("请求出错:", error); }).always(function() { $("#submitBtn").prop('disabled', false); $("#loading").addClass('hide').removeClass('show'); }); }); }); </script> <!-- ./post form data -->
内容的提问来源于stack exchange,提问作者Manish Shahi
相关产品推荐
相关产品推荐

