[英]Saving form submitted data to CSV file using Javascript / JQuery
Trying to submit form data (name and lastname) to a csv file which is stored in the same directory as the html file. 尝试将表单数据(名称和姓氏)提交给与html文件存储在同一目录中的csv文件。 Has to be either JavaScript or JQuery because im injecting this into a SquareSpace website which only supports JS.
必须是JavaScript或JQuery,因为将其注入仅支持JS的SquareSpace网站。
So far I have been able to serialize the form data into an array which returns 到目前为止,我已经能够将表单数据序列化为一个数组,该数组返回
0: {name: "FirstName", value: "John"}
1: {name: "LastName", value: "Doe"}
Spent a couple of hours trying to save this array information into my comments.csv file, to no avail. 花了几个小时试图将此数组信息保存到我的comments.csv文件中,但无济于事。
Here's the code: 这是代码:
<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>
I want to get the firstname and lastname underneath appropriate columns in the csv file. 我想在csv文件中的适当列下获取名字和姓氏。 Firstname being 1st column and lastname being 2nd column, in a way that I will be able to display this information in an html table later on.
名字是第一列,姓氏是第二列,这样我以后就能在html表中显示此信息。
You have to parse your form data into CSV format and trigger a link to download. 您必须将表单数据解析为CSV格式并触发下载链接。 See implementation below
见下面的实施
<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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.