【发布时间】:2015-04-17 17:20:10
【问题描述】:
我正在尝试使用从 JSON 文件获取信息的 JS 添加到 html 表中。 我不知道为什么这不会在表格上显示任何数据。
JSON 示例
[{"User_Name":"John Doe","score":"10","team":"1"},
{"User_Name":"Jane Smith","score":"15","team":"2"},
{"User_Name":"Chuck Berry","score":"12","team":"2"}];
我的 JS 不工作 :(
<table class="table">
<thead>
<tr>
<th data-field="date">Date</th>
<th data-field="message">Message</th>
<th data-field="votes">Votes</th>
</tr>
<tr>
<script type="text/javascript">
window.onload = function(){
$(document).ready(function () {
$.getJSON("/crestdale/new/db.json", function(raw){
console.log(raw);
var json = raw;
var tr;
console.log(json);
for (var i = 0; i < json.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + json[i].date + "</td>");
tr.append("<td>" + json[i].message + "</td>");
tr.append("<td>" + json[i].votes + "</td>");
$('table').append(tr);
}
});
});
};
</script>
</tr>
</thead>
</table>
新问题!!!
我有一个写入 json 文件的 php 文件,当我尝试使用此脚本添加到 json 文件时,它会使 json 文件不显示。
PHP
<?php
date_default_timezone_set('America/new_york');
$message = $_POST['message'];
$date = date("F j, Y, g:i a");
$fp = fopen('db.json', 'r+');
// Loading existing data:
$json = file_get_contents("db.json");
$data = json_decode($json, true);
// Adding new data:
$data[3] = array('date' => $date, 'message' => $message, 'votes' => $votes);
// Writing modified data:
file_put_contents('db.json', json_encode($data, JSON_FORCE_OBJECT));
fclose($fp);
?>
PHP 之后的 JSON
{"0":{"User_Name":"John Doe","score":"10","team":"1"},"1":{"User_Name":"Jane Smith","score":"15","team":"2"},"2":{"User_Name":"Chuck Berry","score":"12","team":"2"},"3":{"date":"February 16, 2015, 11:06 pm","message":null,"votes":null}}
【问题讨论】:
-
你遇到了什么错误?
-
从来没有错误......@ChrisPietschmann
-
为什么要添加
.date、.message、.votes而您的 JSON 样本有User_Name、score和team?另外,题外话,但你让一些人像你一样发疯:1)把$(document).ready放在window.onload里面; 2)把<script>直接放在<tr>里面。 -
如果您正在获取示例中显示的 JSON,那么它的属性与您尝试在 javascript 中读取的属性不同。
-
首先,window.onload 是多余的。其次,你在
for循环中做了很多你不应该做的事情。不要在任何地方附加任何东西,直到在 for 之外。只需将其全部推入一个临时数组,然后加入一个字符串,然后一次全部追加。你也不需要它在你的表格 HTML 中,因为你正在做它 onDOMReady (aka$(document).ready()) 也没有理由甚至有json因为你没有对raw做任何不同的事情.
标签: javascript html json html-table