【发布时间】:2021-02-26 10:32:26
【问题描述】:
我需要使用 jquery 和 ajax 编写一个函数,在点击头像时,用户可以选择一张图片并上传一张新图片。将其保存在我网站文件的文件夹中。
所以目前我有这个 html:
<img src="images/avatars/<?= $infos['Avatar']; ?>" onclick="setPicture()"
alt="avatar" class="rounded-circle clickable" width="150">
<form class="d-none" id="formAvatar" method="post" enctype="multipart/form-
data">
<input class="d-none" type="file" id="inputAvatar" name="inputAvatar" />
</form>
这是我的脚本:
function setPicture() {
$('#inputAvatar').trigger('click', function() { // So here i trigger a click on the input file when the user click on his profile picture. The input is not visible by default on the page.
let userfile = $('#inputAvatar').val();
if(userfile) { // here i want to check if a file has been selected but it doesn't seems to work
$('#formAvatar').submit(); // Here i submit the form if the previous condition is true
$("#formAvatar").on('submit',(function(e) { // Here if the form is submitted i send the picture to a php treatment page
e.preventDefault();
$.ajax({
type: 'POST',
url: 'traitements/traitement-profil.php',
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data) {
let errorWindow = document.getElementById('erreur');
errorWindow.className = "alert alert-danger my-5 text-center";
errorWindow.innerHTML = data;
}
});
})
)}
});
}
谁能帮帮我?
【问题讨论】:
标签: javascript jquery ajax forms file