[英]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');
}
}
我認為這並不壞。 一些可能的解決方案:
例如:
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.