问题
Below is the Jason data received from service call.
"response": {
"eventSessions": {
"sessions": [
{
"startTime": "07:00:00",
"sessionId": 21234,
"endTime": "08:00:00",
"eventId": 1234,
"modifiedDate": "2010-12-07",
"sessionDate": "2010-12-07",
"numberOfAttendees": 3,
"sessionName": "SessionName",
},
{
"startTime": "09:00:00",
"sessionId": 21235,
"endTime": "10:00:00",
"eventId": 1234,
"modifiedDate": "2010-12-07",
"sessionDate": "2010-12-07",
"numberOfAttendees": 3,
"sessionName": "SessionName",
},
{
"startTime": "07:00:00",
"sessionId": 21248,
"endTime": "08:00:00",
"eventId": 1234,
"modifiedDate": "2010-12-08",
"sessionDate": "2010-12-08",
"numberOfAttendees": 3,
"sessionName": "SessionName",
},
] } }
This is just a part of data. Real data has close to 30 session elements. Need to group sessionID based on Session Date and display as show below format using Jquery. Please note Start time and End time are different for each session. Pls help me out here.
<th width="200" scope="col">Fri, Dec 07</th>
<th width="200" scope="col">Sat, Dec 08</th>
</tr>
<tr>
<td><span><strong>7:00 AM - 8:00 AM</strong><br>
21234</span></a> </td>
<td><span><strong>9:00 AM - 10:00 AM</strong><br>
21235</span></a> </td>
</tr>
<tr> <td><span><strong>7:00 AM - 8:00 AM</strong><br>
21248</span></a> </td>
</tr>
回答1:
Take a look at jQuery Templates: http://api.jquery.com/category/plugins/templates/ https://github.com/jquery/jquery-tmpl
You could write something like:
<script type="text/html" id="myTmpl">
<tr>
<td>${sessionDate}</td>
<td>${startTime}</td>
</tr>
</script>
and then in you ajax request callback:
$("#myTmpl").tmpl(response.eventSessions.sessions).appendTo("#yourTable");
回答2:
You already tried to use a for loop? Because its a object what you get back and everything in object response has a object evenSessions has a object Session and has an object/array so you can us it as an array.
Like:
var return_data = response.eventSessions.session;
var table_body_html = "<table>";
for(var i = 0; i < return_data.length; i++) {
var data = return_data[i];
table_body_html += "<th><td colspan="2"></td></th>";
data.each(function(key, value) {
table_body_html += "<tr><td>"+ key +"</td><td>"+ value +"</td></tr>";
});
}
table_body_html += "</table>";
来源:https://stackoverflow.com/questions/4555225/display-json-data-in-table-format-using-jquery