基本上我有2个或更多表单需要序列化并通过ajax调用发送数据。
我有这些表格:
<form class="lang_block">
<fieldset>
<legend>it</legend>
<input name="language" value="Italiano" type="text">
<input name="data" value="data_it" type="text">
<input name="temp" value="temp_it" type="text">
</fieldset>
</form>
<form class="lang_block">
<fieldset>
<legend>en</legend>
<input name="language" value="English" type="text">
<input name="data" value="data_en" type="text">
<input name="temp" value="temp_en" type="text">
</fieldset>
</form>
而且这个JavaScript函数:
function ConvertFormToJSON(target_form)
{
var form = $(target_form);
var arr = [];
form.each(function()
{
var obj = {};
var sr = $(this).serializeArray();
obj = $.each(sr, function()
{
sr[this.name] = this.value;
});
arr.push(obj);
});
return JSON.stringify(arr);
}
ConvertFormToJSON('.lang_block');
输出:
"[
[
{
"name": "language",
"value": "Italiano"
},
{
"name": "data",
"value": "data_it"
},
{
"name": "temp",
"value": "temp_it"
}
],
[
{
"name": "language",
"value": "English"
},
{
"name": "data",
"value": "data_en"
},
{
"name": "temp",
"value": "temp_en"
}
]
]"
我希望实现的输出:
"[
{
"language": "Italiano",
"data": "data_it",
"temp": "temp_it",
},
{
"language": "English",
"data": "data_en",
"temp": "temp_en",
}
]"
答案 0 :(得分:0)
您正在sr而不是对象上设置值。试一试:
function ConvertFormToJSON(target_form)
{
var form = $(target_form);
var arr = [];
form.each(function()
{
var obj = {};
var sr = $(this).serializeArray();
$.each(sr, function() {
obj[this.name] = this.value;
});
arr.push(obj);
});
return JSON.stringify(arr);
}
ConvertFormToJSON('.lang_block');