每次ajax调用后,我的页面总是重新加载,
我试图采取以下措施,
我已将按钮类型更改为按钮,
我使用过event.preventDefault()
还尝试过event.stopPropagation();
以下是我的app.js
$(document).ready(() => {
$('#importImg').click(function (event) {
event.preventDefault();
event.stopPropagation();
if ($('#image')[0].files[0] != null) {
$('#loading')[0].style.display = '';
var file = $('#image')[0].files[0];
var formData = new FormData();
formData.append('file', file);
console.log(formData);
$.ajax({
url: 'http://127.0.0.1:8000/upload',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: (data) => {
var div = document.getElementById("content");
var image = document.createElement("img");
image.src = data;
image.setAttribute("class", "img-site");
div.appendChild(image);
$('#loading')[0].style.display = 'none';
},
error: (jqXHR, textStatus, errorThrown) => {
console.log(jqXHR);
$('#loading')[0].style.display = 'none';
}
})
} else {
alert('Choose a file first!');
}
})
})
这是我的html:
<div class="addimg" style="margin-top: 5rem;">
<input type="file" class="btn btn-primary" name="image" id="image">
<button id="importImg" class="btn btn-danger">Upload</button><span><img style="width: 25px; margin-left: 5px; display: none" id="loading" src="200.gif" alt=""></span>
</div>
谢谢你!
答案 0 :(得分:0)
尝试关注JS:
$(document).ready(() => {
$('#importImg').click(function (event) {
event.preventDefault();
event.stopPropagation();
if ($('#image')[0].files[0] != null) {
$('#loading')[0].style.display = '';
var file = $('#image')[0].files[0];
var formData = new FormData(event.target);
formData.append('file', file);
console.log(formData);
$.ajax({
url: 'http://127.0.0.1:8000/upload',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: (data) => {
var div = document.getElementById("content");
var image = document.createElement("img");
image.src = data;
image.setAttribute("class", "img-site");
div.appendChild(image);
$('#loading')[0].style.display = 'none';
},
error: (jqXHR, textStatus, errorThrown) => {
console.log(jqXHR);
$('#loading')[0].style.display = 'none';
}
})
} else {
alert('Choose a file first!');
}
})
})
答案 1 :(得分:-1)
添加type =“ button”并从点击处理程序中返回false