【发布时间】:2018-02-02 15:54:09
【问题描述】:
我正在研究 html 和 jquery。我的议程是通过 ajax 以预期的 json 格式以 json 类型发送表单数据。我是新的Json嵌套格式
我有一个数组形式的值
<table class="table" id="tableval">
<thead>
<tr>
<th>Topic</th>
<th>No. of Questions</th>
<th>Marks</th>
<th>Action</th>
</tr>
</thead>
<tbody id="level1topic">
<!--Dynamicaly adding row here-->
</tbody>
</table>
<br />
<td><button style="float:left; margin-right:90px; padding-top: 2px;padding-bottom: 2px" class="label label-success level1addrow">ADD TOPIC</button></td>
<br />
Jquery 动态追加行
$(document).ready(function(){
var n=0;
$(document).on('click', '.level1addrow', function(){
n++;
var tempArray = [];
var button_id = $(this).attr("id");
var template ='<tr id="level1row'+n+'">';
template+='<td>';
template+='<input class="form-control" id="level1topic" type="text" name="level1topic[]" placeholder="Topic name" />';
template+='<input type="hidden" name="level1topicid[]" value="'+n+'" />';
template+='</td>';
template+='<br />';
template+='<td>';
template+='<input class="form-control" id="level1no_que'+n+'" type="number" name="level1no_que[]" placeholder="Number Of questions" min="1" max="10"/>';
template+='</td>';
template+='<br />';
template+='<td>';
template+='<input class="form-control" id="level1top_mark'+n+'" type="number" name="level1top_mark[]" placeholder="Marks" min="1" max="10"/>';
template+='</td>';
template+='<br />';
template+='<td>';
template+='<span id="'+n+'" class="label label-danger level1top_remove" data-toggle="tooltip" title="edit!"><i class="fa fa-remove" id="edittt"></i></span> <span id="'+n+'" class="label label-warning"><i class="fa fa-pencil"></i></span></td>';
template+='</td>';
template+='<br />';
template+='</tr>';
template+='<br />';
template+='</div>';
template+='</div>';
var values = $("input[name='level1topic[]']")
.map(function(){return $(this).val();}).get();
$('#level1topic').append( template );
});
上面的代码是动态获取表中每一行的值并将其存储在数组中的方式。我已经获取了如下所示的所有值
var level1testname=$("#level1title").text();
alert(level1testname);
var level1topics = $("input[name='level1topic[]']")
.map(function(){return $(this).val();}).get();
alert(level1topics);
var level1topicid=$("input[name='level1topicid[]']")
.map(function(){return $(this).val();}).get();
alert(level1topicid);
var level1no_que = $("input[name='level1no_que[]']")
.map(function(){return $(this).val();}).get();
var level1top_mark = $("input[name='level1top_mark[]']")
.map(function(){return $(this).val();}).get();
我的问题是我必须将所有值转换为预期 JSON 格式的 json 格式
JSON 格式
{
"testMainSection": [
{
"name": "Mainsectionname",
"topic": [
{
"id": "topicid1",
},
{
"id": "topicid2",
}
],
}
],
"topic": [
{
"id": "topicid1",
"name": "topic1name"
},
{
"id": "topicid2",
"name": "topic2name"
},
]
}
【问题讨论】: