addEventListener进程未触发

时间:2013-12-03 19:07:48

标签: javascript event-listener

我的代码几乎可以正常运行,但事件监听器“Progress”没有触发,因此我无法跟踪上传的进度。

事件监听器“Load”正在触发,我的其余代码正在执行,所以我很茫然。有没有人有任何建议?

$("#myForm").submit(function(){
var xhr = new XMLHttpRequest();

//Progress Tracking
xhr.upload.addEventListener("progress", function(e){
    if(e.lengthComputable){
        alert('test');
        var percentage = Math.round((e.loaded * 100) / e.total);
        $("#myProgress").innerHTML(percentage + '%');
        $("#Progress").val(percentage);
    }
}, false);

//Added just to test that something was firing.
xhr.addEventListener("load", function(){alert('load');}, false);
xhr.addEventListener("error", function(){alert('error');}, false);
xhr.addEventListener("abort", function(){alert('abort');}, false);

//Status Tracking
xhr.open(this.method, this.action, true);
xhr.setRequestHeader("X-FILENAME", this.name);
xhr.onreadystatechange = function(){
    if(xhr.readyState == 4 && xhr.status == 200){
        $('#myForm')[0].reset();
    }
};

//Submit Data
var fd = new FormData();
fd.append("text", $('#text').val());
fd.append("file", $('#file')[0].files[0]);

xhr.send(fd);
return false;
});

1 个答案:

答案 0 :(得分:2)

当您使用XMLHttpRequest& FormData ...所以现代浏览器(chrome,safari,ie10,ios,android)

这是ajax的一个非常简短的版本。

function ajax(a,b,e,d,c){//Url,callback,method,formdata or{key:val},placeholder
 c=new XMLHttpRequest;
 c.onload=b;
 c.open(e||'get',a);
 c.send(d||null)
}

使用

ajax('index.html',callback);
// does a get query to index.html and calls the callback onload

ajax('upload.php',callback,'post',new FormData(form));
//posts the whole form to the upload.php and calls the callback onload

现在您想要进度事件。

如果你想添加多个事件处理程序,那么

addEventListener是好的,因为你只需要一个进度处理程序xhr.onprogess& xhr.upload.onprogress就足够了。

这样:

function ajax(a,b,e,d,f,g,c){
 c=new XMLHttpRequest;
 !f||(c.upload.onprogress=f);
 !g||(c.onprogress=g);
 c.onload=b;
 c.open(e||'get',a);
 c.send(d||null)
}

在这种情况下,我们破坏了之前创建的函数的可用性,但我们可以做更多。

/*
a=url  -  index.php,data.json,script.js
b=callback - function(){console.log(this.response)}
e=method - post,get ?put ?delete
d=formdata or object - new FormData(form) or {key:val}
f=upload progress func - function(){console.log(e.loaded/e.total*100>>0)}
g=download progress func - ""
c=this is just a placeholder - -----
*/

现在关于你的功能,你只需创建一些简短的代码来完成剩下的工作:

var form;
function uploadProgress(e){
 console.log(e.lengthComputable?(e.loaded/e.total*100>>0)+'%':'NO SIZE');
}
function uploadThatStuff(){
 ajax('upload.php',finish,'post',new FormData(form),uploadProgress);
}
function finish(){
 console.log('upload finished',this.response);
}
window.onload=function(){
 form=document.getElementsByTagName('form')[0];
 form.onsubmit=uploadThatStuff;
}

只需替换yourForm& upload.php ...并添加第二个ajax函数

如果您有问题,请询问

作为测试php,你可以使用

<?php
print_r(array($_FILES,$_POST,$_GET));
?>

修改

带有进度条的完整工作示例

<?php
if($_FILES){
 print_r(array($_FILES,$_POST));
}else{
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Upload</title>
<style>
body>div{
 width:300px;
 height:20px;
 border:1px solid rgba(0,0,0,0.5);
}
body>div>div{
 width:0%;
 height:100%;
 background-color:green;    
}
</style>
<script>
var form,progress,result;
function ajax(a,b,e,d,f,g,c){
 c=new XMLHttpRequest;
 !f||(c.upload.onprogress=f);
 !g||(c.onprogress=g);
 c.onload=b;
 c.open(e||'get',a);
 c.send(d||null)
}
function uploadProgress(e){
 e=e||window.event;
 progress.firstChild.style.width=((e.loaded||e.position)/(e.total||e.totalSize)*100>>0)+'%';
}
function uploadThatStuff(e){
 e=e||window.event;
 e.preventDefault();
 //form.title.value?form.file.files[0]?
 ajax('upload.php',finish,'post',new FormData(form),uploadProgress)
 //:alert('Please add a file'):alert('Please add a title');
}
function finish(e){
 result.textContent=this.response||(e=e||window.event,e.target=e.target||e.srcElement,e.target.response);
}
window.onload=function(){
 form=document.getElementsByTagName('form')[0];
 form.onsubmit=uploadThatStuff;
 progress=document.getElementsByTagName('div')[0];
 result=document.getElementsByTagName('pre')[0];
}
</script>
</head>
<body>
<form>
<input name="title">title<br>
<input type="file" name="file"><br>
<input type="submit" value="Send">
</form>
<div><div></div></div>
<pre></pre>
</body>
</html>
<?php
}
?>

过去在文本文件中保存为upload.php