【问题标题】:Create html table in jQuery from array在jQuery中从数组创建html表
【发布时间】:2016-05-05 05:24:35
【问题描述】:

我的数据库中有一组元素。我使用 ajax(POST 过程)来获取它。现在我想创建一个包含这些元素的表。我不完全知道如何在 jQuery 中做到这一点。我有这个:

$.post('script.php',{login: '1'}, 'json').done(function(data) { 
    results = ''; 
    data.table.forEach(function(row){
        results += '<tr><td>' + row.name + '</td><td>' + row.lastname + '</td><td>' + row.data + '</td></tr>';
    });
    $('#MyTable tbody').html(results);
});

我的脚本是这样的:

header('Content-Type: application/json');
...
$result=mysql_query($query); 
$table = array();
while($row=mysql_fetch_array($result)){
$table[] = $row;
}
$data['table'] = $table;
echo json_encode($data);

编辑: 我纠正了我的错误,现在打开表格时控制台出现错误。它显示:

TypeError: data.forEach is not a function

有人知道这句话的结构应该是什么样子吗?

【问题讨论】:

  • 什么不起作用?
  • 嗯,什么都没有显示...我不确定出了什么问题。我的脚本数组如下: Array ( [0] => 2 [id] => 2 [1] => Roberto [name] => Roberto [2] => Robertos [lastname] => Robertos [3] => 2016-01-27 22:10:18 [数据] => 2016-01-27 22:10:18)
  • 似乎不是该数组中的属性table。试试data.forEach(..。整个 json 结构的样本会有所帮助
  • 检查浏览器控制台是否有错误
  • 错字:row.lastanme 应该是row.lastname。但这不会导致这个问题。

标签: jquery arrays ajax post


【解决方案1】:

我看到你说你的php脚本有数据,所以我猜问题应该是 这一行:

echo json_encode();

应该是

echo json_encode($data);

在你的javascript中我会这样做

$.post('script.php',{login: '1'}, function(data) { 
results = ''; 
$.each(data.table, function(idx, row){
    results += '<tr><td>' + row.name + '</td><td>' + row.lastanme + '</td><td>' + row.data + '</td></tr>';
});
$('#MyTable tbody').html(results);

});

【讨论】:

  • 天哪,谢谢,但这并不能解决整个问题。现在,当我更正我的脚本时,当我打开表格时,我在控制台中出现错误:TypeError: data.forEach is not a function 有人知道它的结构应该是什么样子吗?
  • 感谢您的帮助,但仍然没有显示任何内容(但现在控制台中没有错误)
  • 好吧,这里有 2 个可能的问题,1. 你没有从 php 脚本得到响应,看看你用 console.log(data) 得到了什么 2. 如果有响应,看看你有什么$.each() 循环之后的 console.log(results)
  • 好的,我解决了。问题出在表的名称上……非常感谢老兄。
猜你喜欢
  • 2012-03-21
  • 2014-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-04
  • 2012-11-23
相关资源
最近更新 更多