用于循环的xhr响应不工作
xhr response with for loop not working
我有带for循环的xhr,它在中非常罕见
for(var i = 0; i < this.files.length; i++) {
var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function(e) {
};
xhr.onreadystatechange = function(e) {
if(this.readyState === 4) {
console.log(xhr.responseText);
}
};
var formdata = new FormData();
formdata.append("files", this.files[i]);
console.log(this.files[i]);
xhr.open('POST', 'slike.php');
xhr.send(formdata);
}
我称之为slike.php。它运行得很好,但在responseText上,它不好,有时只从循环中获取最后一个文件,有时获取两个文件(具有相同文本)。我不知道该怎么解决,我到处找,找不到答案。
XHR默认情况下是异步的,因此除非您另有指定(XHR open()
方法中的async=false),否则循环可能在第一个XHR初始化之前就已经完成。
但是循环中代码中的i
(this.files[i]
)指的是循环中相同的i
,因此当第一个XHR开始时,i
可能被分配为this.files.length-1
。这就是为什么你总是只得到最后一个文件。
这就是为什么您必须创建所谓的闭包,以确保您使用的索引是您真正想要使用的索引。
试试这个:
for (var i = 0; i < this.files.length; i++) {
(function(index, files) { // In this closure : parameters of a function in JS
// are available only in the function,
// and cannot be changed from outside of it
var xhr = new XMLHttpRequest(); // variables declared in a function in JS
// are available only inside the function
// and cannot be changed from outside of it
xhr.upload.onprogress = function (e) {
};
xhr.onreadystatechange = function (e) {
if (this.readyState === 4) {
console.log(xhr.responseText);
}
};
var formdata = new FormData();
formdata.append("files", files[index]); // `index` has nothing to do with `i`, now:
// if `i` changes outside of the function,
//`index` will not
console.log(files[index]); // Don't keep `console.log()` in production code ;-)
xhr.open('POST', 'slike.php');
xhr.send(formdata);
})(i, this.files)
}
或者如果真的想按顺序获取文件:
var i = 0,
fileNb = this.files.length;
function getNextFile(file) {
var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function (e) {
};
xhr.onreadystatechange = function (e) {
if (this.readyState === 4) {
console.log(xhr.responseText);
if (++i < fileNb) getNextFile(this.files[i]);
}
};
var formdata = new FormData();
formdata.append("files", file);
console.log(file); // Don't keep `console.log()` in production code ;-)
xhr.open('POST', 'slike.php');
xhr.send(formdata);
}
getNextFile(i);
console.log(xhr.responseText);
您正在访问xhr
的当前值(通常是最后创建的值),而不是事件处理程序所附加的对象。
使用this
,而不是像前一行中那样使用xhr
。
相关文章:
- 响应动画手风琴不工作
- 由于响应中不存在“Access Control Allow Origin”标头,跨域请求停止工作
- 自动完成搜索无法正常工作,请不要迭代$中的所有元素.每个ul-li都会及时显示响应
- ajax响应为空后JQuery无法工作
- 服务工作线程是否可以响应同步 XHR 请求
- Jquery Post与JSON响应工作
- 如何在没有 Web 服务器的情况下做出响应.js工作
- 悬停和焦点上的响应式 jQuery 工具提示无法正常工作
- 如何才能让响应式幻灯片在Internet Explorer中工作
- Ajax关于成功响应不工作的警报c#
- 谷歌表单响应无法从网站上工作
- Wordpress AJAX没有't工作-响应0
- 使用nodeJS和phantomJS返回网络请求和响应,仅在控制台中工作
- 用于循环的xhr响应不工作
- 网站响应能力-Iphone需要双击链接才能工作
- 响应式灯箱无法在iPhone中工作
- 响应滑块需要刷新才能工作
- Ajax响应只工作一次-使用PHP的购物车
- 拼写检查器无法在tinymce 4.0中工作(非JSON响应)
- 如何使脚本工作/响应