Javascript:将数据导出到 .txt 文件

Mis*_*eky 5 javascript jquery web-applications

我是 javascript 新手,我想知道是否可以将数据导出到 txt 文件中。我可以将数据放在警报中,但我希望将其作为 txt 文件下载到客户端系统上。我如何实现这一目标?

SWi*_*ilk 3

目前文件 API:Writer尚未准备好,因此您没有直接的接口来保存文件。

不过,您仍然可以创建一个链接并将文本放入 url 中。

var link = document.createElement('a');
link.href = 'data:text/plain;charset=UTF-8,' + encodeURIComponent(yourTextGoesHere);
link.innerHTML = 'Open the text file';
//set default action on link to force download, and set default filename:
link.download = 'some file name.txt';     

//now put the link somewhere in the html document:
document.body.appendChild(link);
Run Code Online (Sandbox Code Playgroud)

手写,未经测试。应该可以工作,但可能需要调试。

编辑:添加download属性。