【发布时间】:2012-07-30 18:04:22
【问题描述】:
我是一名 Python 程序员,所以不确定如何在 JavaScript 中执行此操作。
示例输入(来自提供 JSON 的 REST 服务):
[{"name": "foo", "id": 1024}, {"name": "bar", "id": 1025}]
输出:
<table>
<thead>
<tr><th>name</th> <th>id</th></tr>
</thead>
<tbody>
<tr><td>foo</td> <td>1024</td></tr>
<tr><td>bar</td> <td>1025</td></tr>
</tbody>
</table>
尝试(据我所知,首先尝试使用JQuery docs 中的列表示例,然后再尝试使其成为表格):
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<ul class="my-new-list"></ul>
<script>
$.getJSON('http://www.servicestack.net/ServiceStack.Northwind/customers?format=json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
</script>
</body>
</html>
我确定这只是我的一些 n00bish 错误,但不确定是什么。能指点一下吗?
最好我想要一个带有字典语法的类似 python 的视图(也许Handlebars 可以提供这个?),这样我就可以去for person in this_list: <tr>person.name</tr>。
【问题讨论】:
-
您遇到错误了吗?您收到服务器的响应了吗?
-
如果你在域之间使用 JSON,你应该研究并理解 JSONP,这里有一篇有用的博客文章:jquery4u.com/json/jsonp-examples/#.UBmDjMie6z4
-
[回复已删除的答案]:是的,基本上我希望它生成一个表,其中动态找到这些字段 ID 并将其设置为表头,并将它们的值设置为每条记录作为表行。这可能是一个普遍的问题。
-
@anAgent:得到一个空白屏幕,什么都没有发生。
-
@JustinJenkins:我很困惑如何用它来代替上面的,也不确定如何使它成为一个漂亮的表格布局。
标签: jquery json rest getjson handlebars.js