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

点击提交按钮后AJAX无响应,求解决表单无刷新提交问题

解决AJAX无响应:表单默认提交行为的坑

我一眼就看出问题出在哪了——你的提交按钮是type="submit",点击它的时候浏览器会同时触发你写的saveExercise()和表单的默认提交行为,后者会直接刷新/跳转页面,导致AJAX请求还没来得及完成就被中断了,所以看起来像是AJAX没响应。下面给你几个可行的解决方案:

方案1:在函数里阻止默认事件

修改你的按钮onclick,把事件对象传进去,然后在函数开头阻止默认行为:

修改后的按钮代码:

<button type='submit' id='saveBtn' class='btn btn-info fa fa-download fa-2x saveBtn' required name="submit" onclick="saveExercise(event)"></button>

修改后的AJAX函数:

function saveExercise(event) {
  // 先阻止表单默认提交行为
  event.preventDefault();
  
  $('.eBlock').each(function (i, contents) { 
    // lots of code here 
  }); 
  
  $.ajax({ 
    url: 'saveJson.php', 
    type: 'POST', 
    data: eBlock, 
    dataType: 'json', 
  }).done(function (response) { 
    // 这里可以加请求成功后的逻辑,比如提示保存成功
    console.log('保存成功:', response);
  }).fail(function(xhr, status, error) {
    // 别忘了加错误捕获,方便排查问题
    console.error('请求失败:', error);
  }); 
}

方案2:把按钮改成普通按钮

直接把按钮的type从submit改成button,这样就不会触发表单的默认提交行为,只执行你的AJAX逻辑:

<button type='button' id='saveBtn' class='btn btn-info fa fa-download fa-2x saveBtn' required name="submit" onclick="saveExercise()"></button>

方案3:用jQuery绑定表单提交事件(更推荐)

这种方式更符合jQuery的事件绑定规范,也能避免内联onclick的维护问题:

// 确保在DOM加载完成后绑定事件
$(document).ready(function() {
  $('#my_form').submit(function(e) {
    // 阻止默认提交行为
    e.preventDefault();
    
    // 执行你的保存逻辑
    $('.eBlock').each(function (i, contents) { 
      // lots of code here 
    }); 
    
    $.ajax({ 
      url: 'saveJson.php', 
      type: 'POST', 
      data: eBlock, 
      dataType: 'json', 
    }).done(function (response) { 
      console.log('保存成功:', response);
    }).fail(function(xhr, status, error) {
      console.error('请求失败:', error);
    }); 
  });
});

然后把按钮的onclick去掉:

<button type='submit' id='saveBtn' class='btn btn-info fa fa-download fa-2x saveBtn' required name="submit"></button>

额外排查点

除了阻止默认行为,还要检查这些地方:

  • 确认eBlock变量已经正确定义并赋值,你的代码里只遍历了.eBlock元素,但没看到组装eBlock数据的逻辑,这会导致AJAX请求没有有效数据
  • 打开浏览器控制台(F12),查看有没有语法错误、变量未定义的报错,这些都会导致函数执行失败
  • 确保jQuery已经正确加载到页面中,否则$会报错,整个函数都无法运行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 10:04:42