简体   繁体   中英

Proper way to append HTML to document with JSON data

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:

  • create a function that takes response as parameter and returns the string: you move the "mess" to a single location and you keep your "main" code clean
  • Template strings (like stated by @dfsq): they keep you code clean but they also have the problems stated by him
  • Dynamically create and include each element one by one:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM