我想在ajax调用中发布对象的javascript数组,但我得到字符串值“[]”。当我尝试console.log数组长度它说零。不能发布对象的javascript数组
以下是代码我使用
var masterFileArray = []; // where I will store the contents
function readMultipleFiles(evt) {
//Retrieve all the files from the FileList object
var files = evt.target.files;
if (files) {
for (var i = 0, f; f = files[i]; i++) {
var r = new FileReader();
r.onload = (function (f) {
return function (e) {
var contents = e.target.result;
masterFileArray.push({name:f.name, contents: contents, type:f.type, size:f.size}); // storing as object
};
})(f);
r.readAsText(f);
}
console.log(masterFileArray);
new Ajax.Request('fileupload.php', {
method: 'post',
parameters: {files: JSON.stringify(masterFileArray)},
onSuccess: function(transport){
var response = transport.responseText;
console.log(response);
}
});
} else {
alert('Failed to load files');
}
}
document.getElementById('upfiles').addEventListener('change', readMultipleFiles, false);
那怎么看起来像检查
什么,我做错了什么?任何帮助将不胜感激,谢谢。
因为你在'onload'异步功能添加的元素,基本上是这样。 'readAsText'不会阻塞并等待文件被读取,所以你的代码在数组填充之前立即继续发出请求。 –
在文件读取器读取文件之前,您正在执行Ajax请求。 – Danmoreng
r.onload被解雇了吗? Console.log里面知道:) –