我需要根据调用API时获得的json响应构建一个表, 调用API并获得JSON工作正常,只是我没有找到任何关于构建表并从x.js传递到x.html的文档。我成功地从json传递了1个参数/值。
我的json看起来像这样:(这是Jenkins API的结果)
{
"builds":
[
{
"duration": 24503,
"id": "2013-12-11_19-48-55",
"number": 33,
"result": "FAILURE",
"timestamp": 1386791335164
},
{
"duration": 24553,
"id": "2013-12-11_19-00-27",
"number": 32,
"result": "FAILURE",
"timestamp": 1386788427803
},
{
"duration": 24237,
"id": "2013-12-11_18-59-51",
"number": 31,
"result": "FAILURE",
"timestamp": 1386788391179
},
JS代码
Meteor.call('jenkinsServiceBuild', function(err, respJson) {
if(err) {
window.alert("Error: " + err.reason);
console.log("error occured on receiving data on server. ", err );
} else {
//window.alert("Success: ");
console.log("respJson: ", respJson.builds[1].id);
//window.alert(respJson.length + ' tweets received.');
var buildsList = respJson.builds[1].id;
Session.set("recentBuilds", respJson.builds[1].id);
}
$('#buildButton').removeAttr('disabled').val('build');
})
},
});
Template.dashboard.helpers({
recentBuilds : function() {
return Session.get("recentBuilds");
//recentBuilds: buildsList
} });
HTML代码
<template name="dashboard">
<div class="control-group">
<div class="controls">
<input type="button" value="build" class="btn btn-info" id="buildButton"/>
</div>
<br><br>
___{{recentBuilds}}___
</template>
由于 RONEN
答案 0 :(得分:2)
您可以在html而不是___{{recentBuilds}}___
<table>
<thead>
<th>Duration</th><th>ID</th><th>Number</th><th>Result</th><th>Timestamp</th>
</thead>
<tbody>
{{#each recentBuilds}}
<tr>
<td>{{duration}}</td>
<td>{{number}}</td>
<td>{{result}}</td>
<td>{{timestamp</td>
</tr>
{{else}}
<tr>
<td colspan="4">No data</td>
</tr>
{{/each}}
</tbody>
</table>
同样在你的回调中,返回所有数据而不是一个值,因此可以通过迭代:
而不是
Session.set("recentBuilds", respJson.builds[1].id);
返回builds
中的所有内容。
Session.set("recentBuilds", respJson.builds);
所以现在因为builds
中的所有内容都是一个数组,当你使用{{#each}}
时,它会在你的html中循环遍历它们并为每个数据创建一行。
答案 1 :(得分:0)
您的HTML
<table id="result">
<tr>
<th>Duration</th><th>ID</th><th>Number</th><th>Result</th><th>Timestamp</th>
</tr>
</table>
你的JS
for (obj in respJson.builds) {
var line = '<tr><td>' + obj.duration + '</td><td>' + obj.id + '</td><td>' + obj.number + '</td><td>' + obj.result + '</td><td>' + obj.timestamp + '</td><td>';
$('#result').append(line);
}
答案 2 :(得分:0)
这可能对你有帮助!。使用jquery ajax getjson
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var data=$.getJSON("test.js",function(data)
{
$.each(data.results,function( key, val )
{
$("div").append(val.jobtitle + " <br/>");
});
});
});
</script>
</head>
<body>
<div></div>
</body>
</html>
&#13;