我正在尝试编写一些jquery代码来从云帐户中检索服务器列表并将其显示在表中。当我加载我的页面时,我的javascript执行并返回正确的JSON,但是当我尝试使用jquery模板生成我的html时,我从来没有得到任何输出。谁能帮我弄明白我的问题在哪里?
用于获取服务器数据的Javascript
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: '../../api/server/getservers',
type: 'POST',
success: function (result) {
$('#serverTemplate').tmpl(result).appendTo('#serverTable');
},
});
});
</script>
Jquery模板Javascript
<script id="serverTemplate" type="text/x-jQuery-tmpl">
{{each servers}}
<tr>
<td>${status}</td>
<td>${name}</td>
</tr>
{{/each}}
</script>
HTML
<table>
<thead>
<tr>
<th>Status</th>
<th>Server Name</th>
</tr>
</thead>
<tbody id="serverTable">
</tbody>
</table>
JSON示例
{
"servers": [
{
"progress": 100,
"id": 11111111,
"imageId": 1,
"flavorId": 1,
"status": "ACTIVE",
"name": "SERVER-1",
"hostId": "abcdefghijklmnopqrstuvwxyz",
"addresses": {
"public": [
"1.1.1.1"
],
"private": [
"2.2.2.2"
]
},
"metadata": {}
},
{
"progress": 100,
"id": 22222222,
"imageId": 2,
"flavorId": 2,
"status": "ACTIVE",
"name": "Server-2",
"hostId": "zxywufvslakdkdkdkdkdkdkdkdk",
"addresses": {
"public": [
"3.3.3.3"
],
"private": [
"4.4.4.4"
]
},
"metadata": {}
}
]
}
答案 0 :(得分:1)
我通过更改成功函数并向数组添加JSON的显式解析来解决了这个问题。
var servers = jQuery.parseJSON(result);
$('#serverTemplate').tmpl(servers).appendTo('#serverTable');