I have an AJAX response in JSON format which looks like this:
{
"color":"DEDE54",
"text":"<p>some text<\/p>"
}`
I want to append it in formatted HTML. Below I just have all of the HTML in a string comment
and add in the variables where they should go. It works, but it looks messy and isn't readable.
Is there a proper way I should be doing this?
appendResponse:function (response) {
if (response !== 'wait'){
var color = response.color;
var text = response.text;
var comment = '<div class="comment"><div class="avatar" style="background:#'+color+'"></div><div class="text">'+text+'<div class="date">Just now</div></div></div>';
$('#comment-form').after(comment);
} else {
Materialize.toast('Wait 20 seconds between comments', 5000, 'toast-alert');
}
}
I think it isn't that bad. Some possible solutions are:
For example:
var comment = jQuery('<div/>', {
class: 'comment'
});
var avatar = jQuery('<div/>', {
class: 'avatar'
});
$avatar.css("background-color",response.color);
avatar.appendTo(comment);
.....
.....
However, one thing i wanted to point is that your code seems vulnerable to XSS : it is not a good practice to include HTML elements directly from a webservice as in your example because you can't escape characters (the better and easier way to prevent XSS). Maybe you already know that but in case you don't, take care of it
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.