问题
I am trying to write some jquery code to retrieve a list of servers from a cloud account and display them in a table. When I load my page, my javascript executes and the proper JSON is returned, but when I try to use a jquery template to generate my html, I never get any output. Can anyone help me figure out where my problem is?
Javascript to fetch server data
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: '../../api/server/getservers',
type: 'POST',
success: function (result) {
$('#serverTemplate').tmpl(result).appendTo('#serverTable');
},
});
});
</script>
Jquery Template 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 Example
{
"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": {}
}
]
}
- jQuery version 1.5.1
- jQuery-tmpl version beta 1
回答1:
I solved the issue by changing the success function and adding an explicit parse of the JSON to an array.
var servers = jQuery.parseJSON(result);
$('#serverTemplate').tmpl(servers).appendTo('#serverTable');
来源:https://stackoverflow.com/questions/6508902/how-do-i-use-jquery-templates-with-json-data