javascript - 试图将文本文件加载到
标签,为什么它不起作用?
问题描述
我一直在查看与此相关的其他 stackoverflow 问题,但我不明白为什么这段代码不起作用。现在我首先只是试图将文本获取到控制台日志,看看它是否会起作用。我正在逐行跟踪其他人的代码,它不适用于这种情况,我不确定为什么。
const file = "1.txt";
let reader = new FileReader();
reader.onload = (e) => {
const file = e.target.result;
const lines = file.split(/\r\n|\n/);
console.log(lines.join('\n'));
};
reader.readAsText(file);
解决方案
对于其他遇到此特定问题的人,我发现 fetch() 函数是我的问题的关键。如果您执行以下操作:
fetch('1.txt')
.then(response => response.text())
.then(data => {
// Do something with your data
console.log(data);
});
感谢我收到的所有评论,它帮助我找到了这个解决方案!
推荐阅读
- sql - 查询将两条记录合并为一条
- optimization - Pyomo:如何为每个 (i,j) 对编写约束
- css - Ruby on Rails 6 how to reference images from asset pipeline for css
- botframework - AAD 身份验证 Directline & Teams,禁用安全代码
- python - 使用枕头识别数独网格中的数字
- flutter - Flutter spaceBetween 在 Card 小部件内的 Column 中不起作用
- python-3.x - 在列表对象列表中,如何将每个列表对象与所有其他列表对象进行比较?
- angular - 我可以创建多个 MsalService 实例吗
- r - 从 R 中的 for 循环创建数据框,其中包含 if-else 语句
- scala - 是否有理由使用 s String 插值而不是 f String 插值?