点击‘View Leads’按钮触发多次AJAX请求的修复方案
解决点击"View Leads"按钮发送多次AJAX请求的问题
在Web应用中,多个"View Leads"按钮点击时会触发多次相同的AJAX请求,已尝试全局isRequestInProgress标志但未解决问题,使用jQuery开发。
问题分析
你当前使用的全局isRequestInProgress标志是所有按钮共享的,它会阻止所有按钮的请求,但如果是同一个按钮点击触发多次请求,大概率是以下原因:
- 事件绑定重复:页面动态渲染时多次执行事件绑定逻辑,导致同一个按钮的点击事件被绑定了多个处理器
- 全局标志逻辑缺陷:无法区分不同按钮的请求状态,反而可能误阻止其他正常按钮的操作
解决方案
方案1:针对单个按钮禁用(推荐)
不需要全局标志,点击按钮后直接禁用当前按钮,请求完成后再恢复可用。这样既保证同一个按钮不会重复触发请求,也不影响其他按钮的正常操作:
jQuery(document).ready(function($) { // 事件委托绑定点击事件 $(document).on('click', '.view-leads-btn', function(e) { e.preventDefault(); const $btn = $(this); const carId = $btn.data('carid'); // 如果按钮已禁用,直接返回 if ($btn.is(':disabled')) return; // 禁用按钮并添加加载状态(可选) $btn.prop('disabled', true).addClass('btn-loading'); // 发送AJAX请求 $.ajax({ type: "POST", url: "https://mywebsite.ca/ajax2.php", data: { carId: carId }, dataType: "json", success: function(response) { // 请求完成后恢复按钮状态 $btn.prop('disabled', false).removeClass('btn-loading'); if (response && response.data) { let tableHtml = '<table id="leads-table" class="display nowrap" style="width: 100%"><thead><tr><th>ID</th><th>Mobile</th><th>Time</th><th>Status</th></tr></thead><tbody>'; response.data.forEach(function(item) { tableHtml += `<tr><td>${item.id}</td><td>${item.mobile}</td><td>${item.time}</td><td>${item.status}</td></tr>`; }); tableHtml += '</tbody></table>'; Swal.fire({ title: 'Leads Data', html: tableHtml, confirmButtonText: 'Close', customClass: { container: 'custom-sweetalert2-container' }, width: '90%', responsive: true, breakpoints: { 768: { width: '95%' } } }).then(() => { // 弹窗关闭后销毁DataTable实例,避免重复初始化报错 $('#leads-table').DataTable().destroy(); }); $('#leads-table').DataTable({ scrollX: true, scrollCollapse: true, autoWidth: false }); } }, error: function() { // 错误时也要恢复按钮状态 $btn.prop('disabled', false).removeClass('btn-loading'); Swal.fire({ icon: 'error', title: 'Oops...', text: 'Something went wrong while fetching data!', confirmButtonText: 'Close' }); } }); }); });
方案2:确保事件只绑定一次
如果问题是事件被重复绑定(比如页面动态加载时多次执行$(document).ready),可以在绑定前先解绑该事件,避免重复绑定:
jQuery(document).ready(function($) { let isRequestInProgress = false; function handleViewLeadsClick(carId) { if (isRequestInProgress) return; isRequestInProgress = true; // 原AJAX请求逻辑... $.ajax({ // ...请求配置 success: function(response) { isRequestInProgress = false; // 原success逻辑... }, error: function() { isRequestInProgress = false; // 原error逻辑... } }); } // 绑定前先解绑,确保事件只绑定一次 $(document).off('click', '.view-leads-btn').on('click', '.view-leads-btn', function(e) { e.preventDefault(); const carId = $(this).data('carid'); handleViewLeadsClick(carId); }); });
额外优化建议
- 给禁用的按钮添加加载样式(比如灰化、显示loading图标),提升用户体验
- 弹窗关闭后销毁DataTable实例,避免下次打开弹窗时初始化报错
内容的提问来源于stack exchange,提问作者Aamir Khan
相关产品推荐
相关产品推荐

