I have been upgrading legacy pages to load data with AJAX.
The ajax call returns an object with custom properties
{
item: {
id: 1,
name: 2,
...
}
}
In my AJAX call I am building the elements
$.post("./url/returns-json", query, function(data) {
var response = JSON.parse(data);
$.each(response , function(i, v){
var r = '<div class="style-this"><p>';
var r += v.name;
var r += '</p></div>';
$("item-wrap").append(r);
});
});
is there another way to wrap json response in HTML for display.
This method can get very untidy when building big HTML elements
The best approach might be this:
$('#item-wrap').append(
$('<div>').addClass('style-this').append(
$('<p>').text(v.name)
)
);
In my opinion, jQuery is actually great to dynamically build HTML structures. By indenting the code, the structure is visible very well and utility functions such as text
allow you to insert content safely (see XSS).
I assumed item-wrap
was actually an element identifier, not a tag name. This does not affect my answer.
You can and probably should use jQuery DOM Manipulation Methods. This can seem longer and maybe even more tedious when you just want to add a couple of elements, but when you do detailed and extensive dom manipulation, using jQuery methods make it much more sustainable and easy to read.
$.each(response, function(i, v) {
var div = jQuery("<div>").addClass("style-this"),
p = jQuery("<p>").text(v.name);
p.appendTo(div);
div.appendTo($("item-wrap"));
});
While you can shorten this by adding appends to each other, when you adding any more than two or three elements, and if they have additional manipulation done on them, chaining them makes it very hard to read.
Have you looked at Mustache as a templating engine?
I personally use something similar to this:
var template='<div class="style-this"><p>{{name}}</p></div>',
results=[];
$.each(response , function(i, v){
results.push(template.replace('{{name}}',v.name));
});
$("item-wrap").append(results.join(''));
Another way would be to create a simple "template" function you can pass an object to:
function format(template, map) {
return template.replace(/{([a-z_]+[a-z0-9_]*)}/gi, function(tag, name) {
return map[name] ? map[name] : '';
});
}
// example
alert(format('test {ex} or {deus} {blank}', {'ex' : 'me', 'deus' : 'yourself'}));