【发布时间】:2018-04-08 11:46:56
【问题描述】:
我想通过 ajax 将文件的内容发送到我的服务器端。 我正在使用 FileReader 在客户端读取文件并将其发送到我的服务器端,如下所示:
function readFile(file) {
var content = "";
var reader = new FileReader();
reader.onload = function(e) {
content = reader.result;
console.log(content);
}
console.log(content);
reader.readAsText(file);
return content;
}
var data = {};
data.content = readFile(file);
data.surname = surname;
data.first = firstname;
console.log(data);
sendData(data, global_url + '/instance');
function sendData(data, url) {
console.log("Try to send the data");
$.ajax({
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json',
url: url,
success: function (data) {
console.log('success');
console.log(JSON.stringify(data));
if (data === 'done')
{
window.location.href = "/";
} else {
alert('Error');
}
},
error: function () {
console.log('process error');
}
});
}
但是,我不知道如何返回变量。 函数 readFile 中的第二个 console.log 等于 ""。
【问题讨论】:
-
reader.onload是async,所以console.log(content);是"" -
好的,可以返回内容吗? @xianshenglu
-
将
sendData(data, global_url + '/instance');放入readFile()。 -
如果没有,有没有办法删除异步?做一个同步函数?@AjAX.
标签: javascript client-server filereader