这是我的JSON数据:
{
"0": {
"counthigh": 33,
"loc": "Barangay 7",
"countmedium": 25,
"countlow": 31
},
"1": {
"counthigh": 27,
"loc": "Barangay 6",
"countmedium": 31,
"countlow": 15
},
"2": {
"counthigh": 17,
"loc": "Comagascas",
"countmedium": 38,
"countlow": 10
},
"3": {
"loc": "Barangay 3",
"countmedium": 3,
"countlow": 16
}
}
我希望它在我的数据表中使用,到目前为止尝试了这个:
$(document).ready(function () {
var tbl_barangay = $('#jsontable_brgy').dataTable();
$.ajax({
url: 'tbl/',
dataType: 'json',
success: function (s) {
tbl_barangay.fnClearTable();
for (var i = 0; i < s.length; i++) {
tbl_barangay.fnAddData([
s[i]['locat'],
s[i]['countlow'],
s[i]['countmedium'],
s[i]['counthigh']]);
}
},
error: function (e) {
alert(e);
}
});
});
它没有在表上显示任何内容,也没有抛出任何错误。有帮助吗?我一直在搞清楚但却失败了。
答案 0 :(得分:1)
您正试图循环Object
,就像它是Array
一样。
$(document).ready(function() {
var tbl_barangay = $('#jsontable_brgy').dataTable();
$.ajax({
url: 'tbl/',
dataType: 'json',
success: function(s) {
tbl_barangay.fnClearTable();
for (var key in s) {
if (s.hasOwnProperty(key)) {
var obj = data[key];
tbl_barangay.fnAddData([
obj['loc'] || 0,
obj['counthigh'] || 0,
obj['countlow'] || 0,
obj['countmedium'] || 0
]);
}
}
},
error: function(e) {
alert(e);
}
});
});
由于您正在使用数据表,我认为您正在努力做到这一点 - 数据表提供了开箱即用的此功能 - http://www.datatables.net/examples/ajax/objects.html 您的数据结构稍微偏离了一点。
这是一个正常工作的演示版(你也错过了&#34; 3&#34;上的一个属性,我在下面添加了它):
var data = {
"0": {
"counthigh": 33,
"loc": "Barangay 7",
"countmedium": 25,
"countlow": 31
},
"1": {
"counthigh": 27,
"loc": "Barangay 6",
"countmedium": 31,
"countlow": 15
},
"2": {
"counthigh": 17,
"loc": "Comagascas",
"countmedium": 38,
"countlow": 10
},
"3": {
"loc": "Barangay 3",
"countmedium": 3,
"countlow": 16,
"counthigh": 3,
}
};
$(document).ready(function() {
var tbl_barangay = $('#jsontable_brgy').dataTable();
tbl_barangay.fnClearTable();
for (var key in data) {
if (data.hasOwnProperty(key)) {
var obj = data[key];
tbl_barangay.fnAddData([
obj['loc'],
obj['counthigh'],
obj['countlow'],
obj['countmedium']
]);
}
}
});
&#13;
<link href="//cdn.datatables.net/1.10.5/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="//cdn.datatables.net/1.10.5/js/jquery.dataTables.min.js"></script>
<table id="jsontable_brgy">
<thead>
<tr>
<th>Location</th>
<th>High</th>
<th>Medium</th>
<th>Low</th>
</tr>
</thead>
</table>
&#13;