How do I use jquery templates with JSON data?

浪子不回头ぞ 提交于 2019-12-12 17:24:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!