I have an already rendered template and I want to update it with some JSON data I obtain via AJAX.
The template as it is before rendering looks like this (using jinja2
template engine):
<table>
<thead>
<th> Time </th>
<th> Destination </th>
<th> Bus number </th>
</thead>
<tbody id="table-body">
{% for bus in buses %}
<tr>
<td> bus[0] </td>
<td> bus[1] </td>
<td> bus[2] </td>
</tr>
{% endfor %}
</tbody>
</table>
And I want to send AJAX requests to update the buses
var with new values. The way I do it is deleting the tbody
content when new data arrives, and rendering everything again with the new data.
function executeQuery() {
$.ajax({
method: 'get',
url: '/data/json',
data: { bus_id : {{ bus_id }} },
success: function(data) {
data = JSON.parse(data);
$('#table-body').html('');
for (i in data){
$('#table-body').append(
"<tr>" +
"<td>" + data[i][0] + "</td>" +
"<td>" + data[i][1] + "</td>" +
"<td>" + data[i][2] + "</td>" +
"</tr>");
};
}
});
How can I improve this code? (FWIW I'm using Flask
)