patternjavascriptMinor
Insert JSON data into rendered template after AJAX call
Viewed 0 times
aftertemplateinsertajaxintocalljsonrendereddata
Problem
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
And I want to send AJAX requests to update the
How can I improve this code? (FWIW I'm using
The template as it is before rendering looks like this (using
jinja2 template engine):
Time
Destination
Bus number
{% for bus in buses %}
bus[0]
bus[1]
bus[2]
{% endfor %}
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(
"" +
"" + data[i][0] + "" +
"" + data[i][1] + "" +
"" + data[i][2] + "" +
"");
};
}
});How can I improve this code? (FWIW I'm using
Flask)Solution
If you're using a jQuery collection more than once, make sure to set a variable, this means you don't have to do unnecessary DOM lookups:
You can probably improve your append code to make it more legible. Personally I prefer utilising the jQuery methods where possible, such as
Since you're just doing a simple
var $table = $('#table-body');You can probably improve your append code to make it more legible. Personally I prefer utilising the jQuery methods where possible, such as
.text(). data = JSON.parse(data);
$table.empty(); // empty is more explicit
// iterate over the data
data.forEach(function (buses) {
// create a new table row and append it
var $row = $('')
.appendTo($table);
// iterate over the buses
buses.forEach(function (bus) {
// create the cell, set the text,
// and append it to the row
$('')
.text(bus)
.appendTo($row);
});
});Since you're just doing a simple
get, you can use jQuery shorthand $.get function:$.get('/data/json', { bus_id : {{ bus_id }} })
.success(function (data) {
// do render
});Code Snippets
var $table = $('#table-body');data = JSON.parse(data);
$table.empty(); // empty is more explicit
// iterate over the data
data.forEach(function (buses) {
// create a new table row and append it
var $row = $('<tr>')
.appendTo($table);
// iterate over the buses
buses.forEach(function (bus) {
// create the cell, set the text,
// and append it to the row
$('<td>')
.text(bus)
.appendTo($row);
});
});$.get('/data/json', { bus_id : {{ bus_id }} })
.success(function (data) {
// do render
});Context
StackExchange Code Review Q#69570, answer score: 6
Revisions (0)
No revisions yet.