简体   繁体   English

如何使用javascript将表单数据附加并保存到txt文件

[英]How to append and save form data to txt file using javascript

I have this html code:我有这个 html 代码:

<form  action="" method="post" id="formToSave">
                <h1>Subscribe For Latest Blogs</h1>
                <p>Please subscribe in my website using your email address for latest updates about my blogs and publications.</p>
                <div class="email-box">
                    <i class="fas fa-envelope"></i>
                    <input class="tbox" type="email" name="email" id ="email" value="" placeholder="Enter Your Email Address">
                    <m><button class="btn" type="submit" name="button" onclick="saveFile()" >Subscribe</button></m>
                </div>
            </form>

And also have this javascript code:还有这个javascript代码:

<script>
    let saveFile = () => {
        const email = document.getElementById('email');
        let data = email.value;
        const textToBLOB = new Blob([data], { type: 'text/plain' });
        }
</script>

I want to save the email address form data to a text file and append further email addresses to that file.我想将电子邮件地址表单数据保存到文本文件中,并将更多电子邮件地址附加到该文件中。 what should I do next?我接下来该怎么做?

First of all, i recommend doing this in a server because browser javascript doesn't have access to the file system and cannot append new text into a file.首先,我建议在服务器中执行此操作,因为浏览器 javascript 无法访问文件系统,也无法将新文本附加到文件中。 However, if you need a text file with the emails given by only one client, the following code might help.但是,如果您需要一个仅包含一个客户提供的电子邮件的文本文件,以下代码可能会有所帮助。 Keep in mind that this will only work on the client's side and it wont help for a subscribe system without a server.请记住,这仅适用于客户端,对于没有服务器的订阅系统无济于事。

 const emailsList = [] function addEmailToList() { const email = document.getElementById('email') const { value } = email emailsList.push(value) } function downloadFile() { const textFile = btoa(emailsList.join('\\n')) const saveElement = document.createElement('a') saveElement.href = `data:text/plain;base64,${textFile}` saveElement.download = 'myList.txt' document.body.appendChild(saveElement) saveElement.click() document.body.removeChild(saveElement) }
 <form action="" method="post" id="formToSave"> <h1>Subscribe For Latest Blogs</h1> <p>Please subscribe in my website using your email address for latest updates about my blogs and publications.</p> <div class="email-box"> <i class="fas fa-envelope"></i> <input class="tbox" type="email" name="email" id="email" value="" placeholder="Enter Your Email Address" /> <m><button class="btn" type="button" name="button" onclick="addEmailToList()">Subscribe</button></m> <m><button class="btn" type="button" name="button" onclick="downloadFile()">Download TextFile</button></m> </div> </form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM