使用jQuery/JavaScript将数据从HTML表单保存到文本文件 [英] Saving a data from html form to text file with jquery/javascript

查看:72
本文介绍了使用jQuery/JavaScript将数据从HTML表单保存到文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的网站创建评论标签并插入HTML表单.

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.

我找不到像C ++的fstream这样的正确方法.我在PHP中找到了一些代码,但是我也不想使用PHP.

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.

有什么办法吗?

推荐答案

您可以使用datauri和锚元素(<a>)的新download属性来实现它,而无需服务器.只需在文本框中随机键入一些内容,然后单击导出",然后查看会发生什么情况:

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:

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>

您可以实现其他类型的文件下载,只需将text/plain更改为正确的MIME类型,并确保正确编码文件内容.例如,<canvas>是生成图像的好方法.

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.

这篇关于使用jQuery/JavaScript将数据从HTML表单保存到文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆