遇到的一个问题,在for循环中上传多个文件。每次都去 new XMLHttpRequest.这个上传是没问题,但服务器将文件处理后,将执行后的结果返回来的时候,就出现了异常。 html
for(i=0;i<files.length;i++) { f=files[i]; xhr = new XMLHttpRequest(); xhr.open("post", "@Url.Action("Fix")", true); xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); var fd = new FormData(); fd.append('file', f); xhr.send(fd); var picsize =f.size / 1024; _html = $("#Lists").html(); _html += '<br/><strong>' + f.name + '</strong>(' + (f.type || "n/a") + ') - ' + picsize.toFixed(2); $("#Lists").html(_html); xhr.onreadystatechange = function () { if(xhr.readyState==4){ if(xhr.status==200){ //do something with xhr.responseText; console.log(xhr.responseText); var data = JSON.parse(xhr.responseText); $("#result").append("<li>" + data.state + ',' + data.file + "</li>"); } } }; }
由于循环过快,在获取旧的xmlHttpreQuest响应的时候,会被最新生成的 xmlhttpRequest覆盖掉,虽然服务端返回的结果是正确的,可是上述代码执行后,显示的响应结果会乱掉,好比最后提交的文件,它的状态会被显示屡次。 浏览器
而后就想,可不能够使用setTimeOut,减缓xmlHttpRequest的生成速度,保证每次的响应被浏览器处理后,新的响应再生成。发现这种写法是得不到延时处理的, 服务器
for(i=0;i<10;i++) { setTimeOut(alert(i)); }for循环无视setTimeOut;
查询相关资料后,递归的用法。 app
var i=0; function al() { i++; if(i<10) setTimeout(function(){alert("i="+i);al()},2000); } al();能够使问题获得解决。
试了一下,确实可行。 post
function upload(f) { xhr = new XMLHttpRequest(); xhr.open("post", "@Url.Action("Fix")", true); xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); var fd = new FormData(); fd.append('file', f); xhr.send(fd); var picsize =f.size / 1024; _html = $("#Lists").html(); _html += '<br/><strong>' + f.name + '</strong>(' + (f.type || "n/a") + ') - ' + picsize.toFixed(2); $("#Lists").html(_html); xhr.onreadystatechange = function () { if(xhr.readyState==4){ if(xhr.status==200){ //do something with xhr.responseText; console.log(xhr.responseText); var data = JSON.parse(xhr.responseText); $("#result").append("<li>" + data.state + ',' + data.file + "</li>"); } } }; } var length = 0; var i = 0; function doit(files) { if(i<length-1) { setTimeout(function() { alert(i); upload(files[i]); doit(files); i++; },3000); } }
好吧,既然要用递归,那就干脆在xmlHttpRequest内部使用递归。
改它的onreadystatechange方法入以下:
xhr.onreadystatechange = function () { if(xhr.readyState==4){ if(xhr.status==200){ //do something with xhr.responseText; console.log(xhr.responseText); var data = JSON.parse(xhr.responseText); $("#result").append("<li>" + data.state + ',' + data.file + "</li>"); if(++i<files.length) upload(files); } } };
问题也能解决。