【发布时间】:2014-06-05 16:20:37
【问题描述】:
我有一个来自服务器的 JSON 响应,看起来像(注意:数据可能或多或少,但结构相同)
{
"events": [{
"id": 852157,
"name": "Adelaide v Brisbane",
"timezone": "Australia/Darwin",
"timezoneOffset": 34200,
"time": 1401987600000,
"timeUtc": "2014-06-05T20:00:00+09:30",
"status": "live",
"wpRef": "852157",
"parentCategoryId": 7,
"parentCategoryName": "Australian Rules",
"categoryId": 9274,
"categoryName": "AFL R26 Matches",
"racingEvent": null,
"raceNumber": null,
"marketCount": 0,
"prefix": null,
"nameSeparator": null,
"markets": [],
"result": null
}, {
"id": 852217,
"name": "Geelong v Carlton",
"timezone": "Australia/Darwin",
"timezoneOffset": 34200,
"time": 1401987600000,
"timeUtc": "2014-06-05T20:00:00+09:30",
"status": "live",
"wpRef": "852217",
"parentCategoryId": 7,
"parentCategoryName": "Australian Rules",
"categoryId": 9274,
"categoryName": "AFL R26 Matches",
"racingEvent": null,
"raceNumber": null,
"marketCount": 0,
"prefix": null,
"nameSeparator": null,
"markets": [],
"result": null
}, {
"id": 852238,
"name": "Carlton v Hawthorn",
"timezone": "Australia/Darwin",
"timezoneOffset": 34200,
"time": 1401987600000,
"timeUtc": "2014-06-05T20:00:00+09:30",
"status": "live",
"wpRef": "852238",
"parentCategoryId": 7,
"parentCategoryName": "Australian Rules",
"categoryId": 9274,
"categoryName": "AFL R26 Matches",
"racingEvent": null,
"raceNumber": null,
"marketCount": 0,
"prefix": null,
"nameSeparator": null,
"markets": [],
"result": null
}]
}
我正在尝试以列表格式显示 JSON 中的“名称”属性。通过 onClick 方法从服务器检索数据。由于返回的 JSON 数据可能会有所不同(即可能超过 3 个事件),我希望动态显示 JSON 数据。
列表的 HTML 视图类似于:
<div id="someID" class="filtering">
<h2>EVENTS</h2>
<ul>
<li><a href="">Name 1</a>
</li>
<li><a href="">Name 2</a>
</li>
<li><a href="">Name 3</a>
</li>
</ul>
<div class="clear"></div>
</div>
这是我的 JS 在点击事件时从服务器获取 JSON 时的样子
var navigation = {
sportSubCategoryBindClick: function (id, parentId) {
$("#" + id).live('click', function () {
var thisEl = this,
categoryId = $(this).attr('id');
$.when(ajaxCalls.fetchEventsForCategory(id, parentId, days.fromToday)).done(function (eventsMap) {
// There are no events
if (eventsMap.events.length == 0) {
$('#mainError').show();
$('div.main').hide();
} else {
$('#' + categoryId).addClass('active');
var events = eventsMap.events;
// If there are events
if (events.length > 0) {
navigation.drawAllEvents(events);
}
}
progressIndicator(false);
});
});
},
drawAllEvents: function (events) {
console.log(events);
}
}
我如何在列表视图(drawAllEvents 函数)中从 JSON 动态填充“名称”字段,如 HTML 标记中所述。可能我需要使用
$.each(result,function(index, value){
// code goes over here
});
但我不确定如何在我的情况下使用它。
【问题讨论】:
标签: javascript jquery json