我有这段代码可以从我使用 ajax 从我的 mysql db 获得的数据中呈现模板。
获取模板数据的代码:
setInterval(function() {
function ajax(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
resolve(this.responseText);
};
xhr.onerror = reject;
xhr.open('GET', url);
xhr.send();
});
}
ajax("http://localhost/tuntiseuranta/dbajax.php").then(function(result) {
var personData = JSON.parse(result);
var i = 0;
$.each(personData, function (index, person) {
//var statusid = Math.random()*statuses.length|0;
var statusid = personData[i].status;
var status = getStatus(statusid);
console.log(status);
var fullName = personData[i].firstname + " " + personData[i].lastname;
// hashing needed so urls stay stable but don't publish employee names to adorable.io
var hash = Math.abs((person + '4a_j.rvs4m9kttqgzh5uBtsw5kh%').hashCode()).toString(36)
var person = {
name: fullName,
status: statusid,
statusClass: status.class,
statusLabel: status.label,
hash: hash
}
if (status.verbose) {
person.verbose = status.verbose[Math.random()*status.verbose.length|0];
}
var html = $.templates('#personTmpl').render(person);
$('.js-persons').append(html);
i++;
})
}).catch(function() {
console.log("ajax error");
});
}, 5000);
在网页中显示模板:
<!-- template for one person -->
<script id="personTmpl" type="text/x-jsrender">
<div class="person person-{{:statusClass}}" data-toggle="modal" data-target="#personStatusModal" data-status-id="{{:status}}" data-person="{{:name}}">
<div class="media">
<div class="person__image pull-right">
<img class="media-object" src="https://api.adorable.io/avatars/120/{{:hash}}" alt="{{:name}}">
</div>
<div class="media-body">
<h4 class="media-heading">{{:name}}</h4>
<div class="person__status">
<span class="label label-{{:statusClass}}">{{if statusLabel}}{{:statusLabel}}{{/if}}{{if statusLabel && verbose}}: {{/if}}
{{if verbose}}<span class="verbose">{{:verbose}}</span>{{/if}}
</div>
</div>
</div>
</div>
</script>
问题在于,模板引擎以这种方式呈现新模板,而不是每次都更新旧模板中的数据。
有什么建议可以让它更新已经渲染的模板而不是渲染一个新模板吗?