【问题标题】:Saving form submitted data to CSV file using Javascript / JQuery使用 Javascript/JQuery 将表单提交的数据保存到 CSV 文件
【发布时间】:2019-09-14 22:56:42
【问题描述】:

尝试将表单数据(姓名和姓氏)提交到与 html 文件存储在同一目录中的 csv 文件。必须是 JavaScript 或 JQuery,因为我将其注入到仅支持 JS 的 SquareSpace 网站。

到目前为止,我已经能够将表单数据序列化为一个返回的数组

0: {name: "FirstName", value: "John"}
1: {name: "LastName", value: "Doe"}

花了几个小时试图将此数组信息保存到我的 cmets.csv 文件中,但无济于事。

代码如下:

<form id="form">
        Type your first name: <input type="text" name="FirstName" size="20"><br>
        Type your last name: <input type="text" name="LastName" size="20"><br>
        <input type="button" value="submit" id="dl" onclick="clearForm();">
      </form>

    <script>
//Clear form once submitted
function clearForm(){
    document.getElementById("form").reset();
}

$(document).ready(function(){  
    $("button").click(function(){  
        var x = $("form").serializeArray();  
    });                                     
});  

//Submit x array into ./comments.csv file


    </script>

我想在 csv 文件的适当列下获取名字和姓氏。 Firstname 是第 1 列,lastname 是第 2 列,这样我以后就可以在 html 表格中显示这些信息了。

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    您必须将表单数据解析为 CSV 格式并触发下载链接。 请参阅下面的实现

           <form id="form">
              Type your first name: <input type="text" name="FirstName" size="20"><br>
              Type your last name: <input type="text" name="LastName" size="20"><br>
              <input type="button" value="submit" id="dl" onclick="submitForm()">
            </form>
    
            <script>
              //Clear form once submitted
              function clearForm(){
                  document.getElementById("form").reset();
              }
    
              function submitForm() {
                var formData = $("form").serializeArray();
                let csv = "data:text/csv;charset=utf-8,"; // accept data as CSV
    
                formData.forEach(function(item) {
                  csv += item.value + ";"; // concat form value on csv var and add ; to create columns (you can change to , if want)
                });
    
                var encodedUri = encodeURI(csv);
    
                // if you want to download
                var downloadLink = document.createElement("a");
                downloadLink.setAttribute("download", "FILENAME.csv");
                downloadLink.setAttribute("href", encodedUri);
                document.body.appendChild(downloadLink); // Required for FF
                downloadLink.click();
                downloadLink.remove();
    
                clearForm();
              }
            </script>
    

    【讨论】:

    • event 并不是所有浏览器中的全局对象。会在其中许多中引发错误
    • 好的,我删除了该行,因为它没用,因为表单使用了类型按钮
    • 我不希望它下载 csv 文件。我已经创建了 csv 文件,如果可能的话,我只想将表单内容插入到 csv 文件中。
    • 如果你已经有一个文件是不可能用javascript编辑他的。您需要使用服务器端语言实现。
    猜你喜欢
    • 2014-11-30
    • 1970-01-01
    • 2014-12-18
    • 1970-01-01
    • 1970-01-01
    • 2012-10-17
    • 1970-01-01
    • 2016-08-16
    • 1970-01-01
    相关资源
    最近更新 更多