如何将表单中的数据保存到JSON字典中?

时间:2016-02-18 15:28:53

标签: html arrays json dictionary

我遇到的问题是尝试将用户输入从表单保存到JSON字典中。我的表单的HTML代码如下:

<!DOCTYPE html>
<html>
<head>
    <title>Untitled Document</title>
    <meta charset="UTF-8">
    <meta name="description" content="">
    <meta name="keywords" content="">
    <script src="store.js" type="text/javascript"></script>
</head>
<body>
<form action="cgi-bin/formmail.pl" method="post">
    Name: <input id="name" type="text" name="name" value="" size="25" maxlength="50" />
    <br/>
    <br/>
    Date: <input id="date" type="date" name="date" value="" size="25" maxlength="50" />
    <br/>
    <br/>
    Location: <input id="location" type="text" name="location" value="" size="25" maxlength="50" />
    <br/>
    <br/>
    Category: <select id="category"><option value="landscape">Landscape</option>
    <option value="portrait">Portrait</option>
    <option value="conceptual">Conceptual</option>
    <option value="street">Street</option>
    <option value="fine art">Fine Art</option>
    <option value="people">People</option>
    <option value="abstract">Abstract</option>
    <option value="nature">Nature</option>
    <option value="architecture">Architecture</option>
    <option value="flower">Flower</option>
    <option value="general">General</option>
    <option value="animal">Animal</option>
    <option value="children">Children</option>
    </select>
    <br/>
    <br/>
    <input type="button" value="Change details" onclick="insert();" />
</form>
    <div id="display">      </div>
</body>
</html>

我之前使用过这样的JS函数:

function insert() {
var nameinput = document.getElementById("name").value;
var dateinput = document.getElementById("date").value;
var locationinput = document.getElementById("location").value;
  var category = document.getElementById("category").value;

var messageBox = document.getElementById("display");
   var details = [nameinput, dateinput, locationinput,category];
  messageBox.innerHTML="Name: " + details[0]+"<br/>"+"Date: " + details[1]+"<br/>"+ "Location: " + details[2]+"<br/>" + "Category: " + details[3];
} 

有谁知道如何实现这一目标的任何提示?谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

您可以使用serializeArray()
例: https://jsbin.com/fokuqaw/edit?html,output

再见^。^