使用 jquery/javascript 将数据从 html 表单保存到文本文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27398074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Saving a data from html form to text file with jquery/javascript
提问by Getdachopa
I'm trying to create a comments tab for my website and insert an HTML form.
我正在尝试为我的网站创建一个评论选项卡并插入一个 HTML 表单。
So far my form and comments tab is ready. I'd like to create a text document to store HTML form inputs.
到目前为止,我的表单和评论选项卡已准备就绪。我想创建一个文本文档来存储 HTML 表单输入。
I couldn't find a proper way to do that, like C++'s fstream
. I found some code with PHP, but I don't want to use PHP either.
我找不到合适的方法来做到这一点,比如 C++ 的fstream
. 我找到了一些 PHP 代码,但我也不想使用 PHP。
Any way to do this?
有什么办法可以做到这一点?
回答by Leo
You can use datauri and new download
property of anchor elements (<a>
) to achive it, without a server. Just randomly type something in the text box, click "export" and see what happens:
您可以使用 datauri 和download
锚元素 ( <a>
) 的新属性来实现它,而无需服务器。只需在文本框中随机输入一些内容,单击“导出”,看看会发生什么:
var container = document.querySelector('textarea');
var anchor = document.querySelector('a');
anchor.onclick = function() {
anchor.href = 'data:text/plain;charset=utf-8,' + encodeURIComponent(container.value);
anchor.download = 'export.txt';
};
<textarea></textarea>
<p><a href="#">Export</a></p>
You can achive other types of file download, just change text/plain
to the proper MIME type, and ensure that you encode the file content correctly. For example, <canvas>
is a good approach for generating images.
您可以下载其他类型的文件,只需更改text/plain
为正确的 MIME 类型,并确保正确编码文件内容。例如,<canvas>
是生成图像的好方法。