0

我正在尝试使用 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;
}
4

2 回答 2

0

尝试

var textToInsert = new Array();
于 2012-09-06T11:55:35.303 回答
0

在你的 for 循环中for (var i = 0; i <length; i += 1)

你不是说长度是多少!它应该是list.length

此外,如果你想这样使用它,你应该声明textToInsert为数组而不是字符串

textToInsert = [];
于 2012-09-06T11:48:27.697 回答