3

我在使用已经由 php 页面生成的 JSON 对象构建 html 表时遇到问题。

我正在从一个电子表格构建我的 JSON 对象,其中包括:Fname、Lname、Ext、Rm。

我的 json.php 网页给了我这个结果:

[{"fName":"John","lName":"Doe","Ext":"#666","Rm":"C3","id":0},{"fName":"Abraham","lName":"Lincoln","Ext":"#917","Rm":"C1","id":1}]

所以现在我正在尝试使用 jquery 构建一个用这些数据填充表格的 html 页面。这是我的 index.html 的内容:

<html>
<head>
    <script src="http://code.jquery.com/jquery-latest.js" type="text/javascript">
    </script>
</head>
<body>
<div id="stuff"
<table id="userdata" border="1">
    <thead>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Ext</th>
        <th>Room</th>
    </thead>
    <tbody></tbody>
</table>
</div>

<script>
$(document).ready(function(){
    $("#userdata tbody").html("");
    $.getJSON("json.php", function(data){
            $.each(data.members, function(i,user){
                var tblRow =
                    "<tr>"
                    +"<td>"+user.fName+"</td>"
                    +"<td>"+user.lName+"</td>"
                    +"<td>"+user.Ext+"</td>"
                    +"<td>"+user.Rm+"</td>"
                    +"</tr>"
                $(tblRow).appendTo("#userdata tbody");
            });
        }
    );
});
</script>

编辑:使用以下代码找到我的解决方案:

<?php
$json = file_get_contents('collab.json.php');
$data = json_decode($json,true);

echo '<table>';
echo '<tr><th>Username</th><th>Period</th><th>Room</th><th>Next?</th></tr>';

$n = 0;

foreach ($data as $key => $jsons) {
    foreach ($jsons as $key => $value) {
        echo '<tr>';
    echo '<td>'.$data[$n]['username'].'</td>';
    echo '<td>'.$data[$n]['period'].'</td>';
    echo '<td>'.$data[$n]['Rm'].'</td>';
    echo '<td>'.$data[$n]['next'].'</td>';
    echo '</tr>';

    $n++;
} 
}
echo '</table>';
?>

</html>
4

2 回答 2

1

假设您提供的 json 是您的唯一输出,您json.php必须稍微更改此行:

$.each(data.members, function(i,user){

对此:

$.each(data, function(i,user){
于 2013-08-13T22:52:15.327 回答
0

通常在这些情况下,我将项目添加到数组中,然后加入并附加数组。例如,在你的每个。

tblRow = [
  '<tr>',
    '<td>' + user.fName + '</td>',
    '<td>' + user.lName + '</td>',
    '<td>' + user.Ext + '</td>',
    '<td>' + user.Rm + '</td>',
  '</tr>',
].join('\n');

myArray.push(tblRow);

myArray 是循环之外的空数组,然后在循环之后将数组内容附加到表中。

希望这可以帮助!

于 2013-08-13T22:55:58.553 回答