dimanche 29 mars 2015

Generating dynamic html from JSON data with jquery

I've been doing a lot of googling and looking for the best way to dynamically generate html. My current solution follows in code snippets. The idea of my code is to grab data from the server and then use the returned array of task items to build dynamic list content.


My question is, surely there is a better, less verbose and more maintainable way of doing this?





// returns an array of task objects from server
$.post("/fetch", JSON.stringify({
"Sort": "tasksperuser"
}), function(data) {
// Generate a task line item in html before appending for each task object.
$.each(data, function() {
console.log($(this));
$("#taskBox").append(taskline);
var tempkey = $(this)[0]['key'];
$("#taskBox > p:last").attr("id", tempkey);
if ($(this)[0]['completed'] == true) {
$("#" + tempkey + " .taskCheckbox").prop('checked', true)
.siblings('.task-title').css("text-decoration", "line-through");
}
$("#" + tempkey + " .task-title").text($(this)[0]['title']);
})
}, "json")
.fail(function() {
console.log("Tasks load per user from server failure.");
});

var taskline = '<p id="" class="taskWrapper">' +
'<input type="checkbox" class="taskCheckbox"/>' +
'<span class="task-title"></span>' +
'<button type="button" class="btn btn-default btn-xs taskDelete pull-right" aria-label="Left Align">' +
' <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>' +
'</button>' +
'<button type="button" class="btn btn-default btn-xs pull-right" data-toggle="modal" data-target="#TaskModal" data-key="" aria-label="Left Align">' +
' <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>' +
'</button>' +
'</p>'



Aucun commentaire:

Enregistrer un commentaire