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

如何阻止Ajax上传视频成功后触发页面自动重新加载

问题根因

页面自动重载是默认行为未拦截导致的:

  • 触发文件选择的<button>标签没有显式声明type属性,如果按钮位于<form>容器内,浏览器会默认将其识别为submit类型的提交按钮,点击时触发表单原生提交,直接跳转重载页面。
  • 绑定在文件选择框上的onchange事件传入了event对象,但UploadVid函数没有接收参数,也没有做默认行为拦截,极端场景下会触发意外的提交逻辑。
修复步骤
  • 给按钮添加type="button"属性,从根源上避免被识别为提交按钮:
<button type="button" onclick="$('#inputVideo').trigger('click')"  class="btn btn-primary text-white">Upload</button>
  • 修改UploadVid函数,接收事件对象并拦截默认行为,同时补充文件非空校验避免空值报错:
function UploadVid(e){
    // 阻止默认事件与冒泡,避免意外触发提交
    e.preventDefault();
    e.stopPropagation();

    const file = $("#inputVideo")[0].files[0];
    if (!file) return;
    const formData = new FormData();
    formData.append("file1", file);

    $.ajax({
        url: 'http://localhost:3000/upload-video',
        method: 'POST',
        data: formData,
        contentType: false,
        processData: false,
        xhr: function () {
            const xhr = new window.XMLHttpRequest();
            xhr.upload.addEventListener("progress", uploadProgressHandler, true);
            xhr.addEventListener("load", loadHandler, false);
            xhr.addEventListener("error", errorHandler, false);
            xhr.addEventListener("abort", abortHandler, false);
            return xhr;
        }
    });
}
  • 兜底处理:如果上传组件外层包裹了form标签,额外给form绑定submit事件拦截原生提交:
// 替换成你实际的form选择器即可
$('form').on('submit', function(e){
    e.preventDefault();
})

改完之后上传逻辑就会完全走自定义Ajax,不会触发页面自动重载。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 15:06:21