[英]How can i prevent ajax request from reloading page
i have this ajax code which post data to by server side but reloads after upload successuful.我有这个 ajax 代码,它通过服务器端发布数据,但在上传成功后重新加载。 i have attached my html code below.
我在下面附上了我的 html 代码。 kindly help out here, thanks
请在这里帮忙,谢谢
function UploadVid(){
var file = $("#inputVideo")[0].files[0];
var formData = new FormData();
formData.append("file1", file);
$.ajax({
url: 'http://localhost:3000/upload-video',
method: 'POST',
data: formData,
contentType: false,
processData: false,
xhr: function () {
var 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);
console.log(xhr)
return xhr;
}
});
}
//html code
<div class="col-4 mt-2">
<label class="col-12">Upload Video File</label>
<button onclick="$('#inputVideo').trigger('click')" class="btn btn-primary text-white">Upload</button>
<input id="inputVideo" onchange="UploadVid(event)" accept="video/*" hidden class="d-none" type="file">
</div>
To fix this, and improve the quality of your code, remove the inline event handler and attach the event using an unobtrusive method to the form
element containing the button.要解决此问题并提高代码质量,请删除内联事件处理程序并使用不显眼的方法将事件附加到包含按钮的
form
元素。 From there you can call preventDefault()
on the event passed to your handler function as an argument to prevent the standard HTTP request caused by the form submission.从那里您可以在作为参数传递给您的处理函数的事件上调用
preventDefault()
以防止由表单提交引起的标准 HTTP 请求。
In addition, as suggested by @Christopher, add type="button"
to the button so that it will not submit the form when you click it to select a file to upload.另外,正如@Christopher 所建议的,将
type="button"
添加到按钮中,这样当您单击它以选择要上传的文件时,它就不会提交表单。
Try this:尝试这个:
$('#yourForm').on('submit', e => {
e.preventDefault();
var file = $("#inputVideo")[0].files[0];
var formData = new FormData();
formData.append("file1", file);
$.ajax({
url: 'http://localhost:3000/upload-video',
method: 'POST',
data: formData,
contentType: false,
processData: false,
xhr: function() {
var 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;
}
});
});
$('.upload-btn').on('click', () => {
$('#inputVideo').trigger('click');
});
<div class="col-4 mt-2">
<label class="col-12">Upload Video File</label>
<button type="button" class="btn btn-primary text-white">Upload</button>
<input type="file" id="inputVideo" hidden class="ulpoad-btn d-none" />
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.