表单提交显示带loading gif的加载提示,完成后跳转的实现排错
问题排查
你的代码有两个核心问题导致效果不符合预期:
- 加载动效不显示:你只控制了父容器
#loader的显示属性,容器内部的gif图片写了内联样式display:none,始终处于隐藏状态;同时#loader本身没有设置初始隐藏,页面打开时就会出现空白占位。 - 无结果展示/页面跳转:你用
e.preventDefault()阻止了表单默认的提交跳转行为,但AJAX请求成功后,既没有把PHP返回的表格内容渲染到页面,也没有编写跳转逻辑,因此请求发送完成后页面没有任何变化。
修正方案
加载层直接做成半透明全屏模态框,提交表单时立刻触发显示,AJAX拿到PHP返回的表格内容后直接渲染到页面,同时隐藏加载层,不需要二次跳转,体验更流畅。如果你确实需要跳转到独立的PHP结果页,可以在success回调里加跳转逻辑,但注意这种方式会重新发起一次请求。
修正后的jQuery代码
$(function(){ const $form = $('#date_range'); const $loader = $('#loader'); const $resultContainer = $('#result_container'); $form.submit(function(e){ e.preventDefault(); const formData = $form.serialize(); // 提交瞬间立刻显示加载模态框 $loader.css("display", "flex"); // 清空之前的查询结果 $resultContainer.empty(); $.ajax({ type: 'POST', url: 'test_loading_gif.php', data: formData, success: function(res){ // 请求成功,隐藏加载层,插入返回的表格内容 $loader.hide(); $resultContainer.html(res); }, error: function(){ // 请求失败也要隐藏加载层,给用户提示 $loader.hide(); alert('查询请求失败,请重试'); } }); }); });
修正后的HTML代码
<!-- 全屏加载模态框,默认隐藏 --> <div id="loader" style="display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);z-index:9999;justify-content:center;align-items:center;"> <img src="loading.gif" alt="加载中"> </div> <div style="width: 60%;margin: auto;display: flex;justify-content: center;"> <form id="date_range"> <label for="first_date">Beginning Date: <input type="date" name="first_date" id="first_date" required> </label> <label for="2nd_date">End Date: <input type="date" name="second_date" id="second_date" required> </label><br> <input type="submit" value="Search"> </form> </div> <!-- 查询结果渲染容器 --> <div id="result_container" style="width:80%;margin:2rem auto;"></div>
补充说明:如果你的PHP文件是直接输出完整的HTML页面(而不是仅输出表格片段),可以把success回调里的内容替换为
document.write(res),直接用返回的内容替换当前页,效果和跳转一致,且不会重复发起请求。
内容的提问来源于stack exchange,提问作者SkylarP
相关产品推荐
相关产品推荐

