我正在尝试使用 jQuery 用 json 数据填充表格。但 div 内容保持为空。请帮我找出错误。该数组list
包含数据(我用 进行了检查console.log(list)
)。另外list['Var1']
和list['Var2']
参考由键Var1
和指定的值Var2
。问题正是在 jQuery 中。
function loadData() {
$.getJSON(
'modules/getData.php',
function(data) {
var list = data.flights;
var textToInsert = '';
console.log(list);
for (var i = 0; i < list.length; i += 1) {
textToInsert[i++] = '<tr><td>';
textToInsert[i++] = list['Var1'];
textToInsert[i++] = '</td>' ;
textToInsert[i++] = '<td>';
textToInsert[i++] = list['Var2'];
textToInsert[i++] = '</td> </tr>' ;
}
$('#flights_table tbody').append(textToInsert.join(''));
}
);
}
<div id="flights_table" style="display:none;">
<table id="newspaper-b" border="0" cellspacing="2" cellpadding="2" width = "100%">
<thead>
<tr>
<th scope="col">Var1</th>
<th scope="col">Var2</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
获取数据.php
$list = array();
//fill the list using 'keys' and 'values'
echo json_encode(array('flights' => $list));
die();
UDPATE:包括 list.length。但萤火虫仍然说
TypeError:textToInsert.join 不是函数
解决方案:解决方案是使用这个:
for (var i = 0; i < list.length; i++) {
aux = list[i];
textToInsert += '<tr><td>';
textToInsert += aux.Var1;
}