gpt4 book ai didi

javascript - 文件上传后显示对话框(Ajax/PHP/Javascript)

转载 作者:行者123 更新时间:2023-12-03 10:13:55 25 4
gpt4 key购买 nike

所以我使用 Javascript 和 AJAX 将表单数据发送到 PHP 文件。将文件上传到服务器后,我希望出现一个对话框,表明已成功,然后重新加载。我已经完成了该对话框,但即使有错误它也会出现。我虽然创建一个标志可以解决这个问题,但事实并非如此。我需要等待进度100%完成,所以我将代码放在progress函数中。这是我的代码:

function uploadImage(){  
var done = false;
var xr = new XMLHttpRequest();
xr.upload.addEventListener("progress", progressHandler, false);
xr.addEventListener("error", errorHandler, false);
xr.addEventListener("abort", abortHandler, false);
xr.open("POST", "php/uploadImage.php", true);

xr.onreadystatechange = function(){
if(xr.readyState == 4 && xr.status == 200){
var response = xr.responseText;
if(response=="success"){
done=true;
}else{
_("errorMessage").innerHTML = response;
}
}
}

xr.send(formdata);

function progressHandler(event){
var percent = (event.loaded / event.total) * 100;
_("imageUploadBar").style.width = Math.round(percent) + "%";

if((percent == 100) && (done)){
completeHandler();
}
}

function completeHandler(){
bootbox.dialog({
message: "Image upload is completed.",
title: "Upload Success",
buttons: {
success: {
label: "Continue",
className: "btn btn-success",
callback: function() {
location.reload();
}
}

}
});
}
}

所以你可以看到,如果上传文件返回成功,则将done设置为true,如果percent为100,则触发,但这不会触发completeHandler()函数。有什么想法为什么或如何解决这个问题吗?

最佳答案

我相信这通常会从 onreadystatechange 触发,但添加第二个变量应该可以解决您的问题。

var done = false;
var uploaded = false;
var xr = new XMLHttpRequest();
xr.upload.addEventListener("progress", progressHandler, false);
xr.addEventListener("error", errorHandler, false);
xr.addEventListener("abort", abortHandler, false);
xr.open("POST", "php/uploadImage.php", true);

xr.onreadystatechange = function(){
if(xr.readyState == 4 && xr.status == 200){
var response = xr.responseText;
if(response=="success"){
done=true;
if(uploaded && done){
completeHandler();
}
}else{
_("errorMessage").innerHTML = response;
}
}
}

xr.send(formdata);

function progressHandler(event){
var percent = (event.loaded / event.total) * 100;
_("imageUploadBar").style.width = Math.round(percent) + "%";

if(percent == 100) uploaded = true;

if(uploaded && done){
completeHandler();
}
}

function completeHandler(){
bootbox.dialog({
message: "Image upload is completed.",
title: "Upload Success",
buttons: {
success: {
label: "Continue",
className: "btn btn-success",
callback: function() {
location.reload();
}
}

}
});
}

关于javascript - 文件上传后显示对话框(Ajax/PHP/Javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29980442/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com