簡體   English   中英

使用JSON數據將HTML附加到文檔的正確方法

[英]Proper way to append HTML to document with JSON data

我有一個JSON格式的AJAX響應,如下所示:

{
  "color":"DEDE54",
  "text":"<p>some text<\/p>"
}`

我想以格式化的HTML附加它。 下面我只是在字符串comment包含所有HTML,並添加它們應該去的變量。 它有效,但它看起來很亂,不可讀。

有沒有正確的方法我應該這樣做?

  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');
    }
  }

我認為這並不壞。 一些可能的解決方案:

  • 創建一個將響應作為參數並返回字符串的函數:將“混亂”移動到一個位置,並保持“主”代碼清潔
  • 模板字符串(如@dfsq所述):它們可以保持代碼清潔,但它們也存在問題
  • 動態創建並逐個包含每個元素:

例如:

var comment = jQuery('<div/>', {
    class: 'comment'
});

var avatar = jQuery('<div/>', {
    class: 'avatar'
});

$avatar.css("background-color",response.color);
avatar.appendTo(comment);
.....
.....


但是,我想指出的一件事是你的代碼似乎容易受到XSS的影響 :在你的例子中直接從webservice中包含HTML元素並不是一個好習慣,因為你無法轉義字符(更好更容易預防XSS)。 也許你已經知道了,但萬一你沒有,請照顧它

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM