如何将表单的所有元素转换为JavaScript对象?
我想有一些方法从我的表单中自动构建一个JavaScript对象,而不必遍历每个元素.我不想要返回的字符串,$('#formid').serialize();也不想要返回的地图$('#formid').serializeArray();
是否有一种简单的单行方式来获取表单的数据,如果它是以经典的HTML方式提交的话?
例如,在:
<form>
<input type="radio" name="foo" value="1" checked="checked" />
<input type="radio" name="foo" value="0" />
<input name="bar" value="xxx" />
<select name="this">
<option value="hi" selected="selected">Hi</option>
<option value="ho">Ho</option>
</form>
Run Code Online (Sandbox Code Playgroud)
日期:
{
"foo": "1",
"bar": "xxx",
"this": "hi"
}
Run Code Online (Sandbox Code Playgroud)
这样的事情太简单了,因为它没有(正确地)包括textareas,选择,单选按钮和复选框:
$("#form input").each(function () {
data[theFieldName] = theFieldValue;
});
Run Code Online (Sandbox Code Playgroud) 所以我有这个HTML表单:
<html>
<head><title>test</title></head>
<body>
<form action="myurl" method="POST" name="myForm">
<p><label for="first_name">First Name:</label>
<input type="text" name="first_name" id="fname"></p>
<p><label for="last_name">Last Name:</label>
<input type="text" name="last_name" id="lname"></p>
<input value="Submit" type="submit" onclick="submitform()">
</form>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
当用户点击提交时,这是将此表单的数据作为JSON对象发送到我的服务器的最简单方法?
更新:我已经走了这么远,但它似乎不起作用:
<script type="text/javascript">
function submitform(){
alert("Sending Json");
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action, true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
var j = {
"first_name":"binchen",
"last_name":"heris",
};
xhr.send(JSON.stringify(j));
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?