【问题标题】:How do I use jquery templates with JSON data?如何使用带有 JSON 数据的 jquery 模板?
【发布时间】:2011-09-24 10:23:28
【问题描述】:

我正在尝试编写一些 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": {}
        }
    ]
}
  • jQuery 版本 1.5.1
  • jQuery-tmpl 测试版 1

【问题讨论】:

  • 如果处理 ajax 请求没有问题,我看不到任何其他问题。它对我来说很好。检查jsfiddle.net/E2cKh
  • JSON 解析得很好吗?我想知道我是否缺少 JSON 解析库或类似的东西?我在下面发布了我的答案,但很高兴听到我的原始代码对你有用。

标签: c# jquery ajax json jquery-templates


【解决方案1】:

我通过更改成功函数并将 JSON 的显式解析添加到数组中解决了这个问题。

var servers = jQuery.parseJSON(result);
$('#serverTemplate').tmpl(servers).appendTo('#serverTable');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-01
    • 1970-01-01
    • 2013-04-11
    • 2012-01-16
    相关资源
    最近更新 更多