我正在尝试将 HTML 表中存在的数据转换为 JSON,以便可以在服务器端对其进行相应处理。我能够序列化数据,但结果充其量会生成不直接链接的不同数据数组。喜欢:这是我正在使用的表格:
<form id="nameGenderForm">
<table id="nameGenderTable">
<tr>
<th >Name</th>
<th >Gender</th>
</tr>
<tr>
<td><input type="text" name="studentName"></td>
<td>
<select name="studentGender">
<option value="male">male</option>
<option value="female">female</option>
</select>
</td>
</tr>
<tr>
<td><input type="text" name="studentName"></td>
<td>
<select name="studentGender">
<option value="male">male</option>
<option value="female">female</option>
</select>
</td>
</tr>
</table>
<input type="submit" />
</form>
序列化数据的脚本是:
$("#nameGenderForm").submit(function(event){
event.preventDefault();
var rawData=$('#nameGenderForm').serializeFormJSON();
var formData=JSON.stringify(rawData);
console.log(formData);
});
serializeFormJSON() 是我在浏览了几页 StackOverFlow 后得到的:
(function($) {
$.fn.serializeFormJSON = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
})(jQuery);
通过使用所有这些,我能够得到一个像这样的 JSON:
{"studentName":["kenpachi","orihime"],"studentGender":["male","female"]}
我尝试了很多方法来让它们以姓名性别格式出现,但每种方法都会产生相同的结果。两个不同的数组。为每个使用表单也无济于事。有什么方法可以像这样获取 name-gender 数组中的数据:
{"studentName":"kenpachi","studentGender":"male"},{"studentName":"orihime","studentGender":"female"}
请指教。