根据收到的json响应添加行

时间:2016-02-07 05:45:11

标签: javascript jquery html json

我可以输入下面一段代码中提到的多个学生详细信息,方法是单击每行旁边的+符号,如果不需要,则删除bin符号:

<tr class="firstclass" id="school0">
    <td ><input type="text" id="rollnum" name="rollnum" class="rollClass" maxlength="20"/></td>
    <td ><select id="school" name="school" multiple="multiple" style="width: 95px; size: 50px" size="3" class="schoolClass"></td>
    <td><img src="<c:url value="/images/add_small.png"/>" id="btnAdd1" class="addImg"/></td>
    <td><img src="images/delete_small.png" id="btnDelete1" class="delImg"/></td >
</tr>

<tr class="secondclass" id="college0">
    <td ><input type="text" id="rollnum" name="rollnum" class="rollClass" maxlength="20"/></td>
    <td ><select id="college" name="college" multiple="multiple" style="width: 95px; size: 50px" size="3" class="schoolClass"></td>
    <td><img src="<c:url value="/images/add_small.png"/>" id="btnAdd1" class="addImg"/></td>
    <td><img src="images/delete_small.png" id="btnDelete1" class="delImg"/></td >
</tr>

但是,如果我作为json字符串收到了超过1行的数据,那么如何展示它们是棘手的。

$.ajax({
    dataType: "json",
    type: "POST",
    url: 'get_StudentList',
    async: false,
    data: {
        schrollnum: schrollnum,
        school: school,
        colrollnum: collrollnum,
        college: college
    },
    success: function(response) {
        // No clue if I had received around 10 rows of data 
    }

一切都在jquery

2 个答案:

答案 0 :(得分:0)

您可以执行类似此示例的操作,我建议您在chrome中成功调用内添加断点以检查响应数据,或者您可以在编写任何代码之前使用网络选项卡查看响应。代码取决于响应JSON结构,因此请检查chrome developer工具中的网络选项卡以查看响应JSON结构。

$.ajax({
    dataType : "json",
    type : "POST",
    url : 'get_StudentList',
    async : false,
    data : {
    schrollnum: schrollnum,
    school: school,
    colrollnum: collrollnum,
    college: college
    }, 
    success : function(response) {
         //Open your website in chrome and a breakpoint at this line and then you can play with the response data in developer console
         //If your response is in JSON format then you can directly check it like
         if(response.students && response.students.length){
              //Insert elements to DOM from data received
         }
         //If your response is in String format then you will need to parse it
         var studentData = JSON.parse(response);
         if(studentData.students && studentData.students.length){
              //Insert elements to DOM from data received
         }
    }
});

答案 1 :(得分:0)

您可以迭代您的回复并将行追加到表中:

success : function(response) {
    var htmlTemplate = '', schoolId;
    response.aaData.forEach( function(item){
         if ( item.schrollnum ){
             schoolId = item.schrollnum;
         } else {
             schoolId = item.colrollnum;
         }             
         htmlTemplate += '<tr class="firstclass" id="' + schoolId + '"><td>...</td></tr>';
    });

    $('#table').append(htmlTemplate);
}