我有一个myfile.json
文件是这样的:PHP代码读取JSON文件
[{"teamA": {"name": "DAR", "games": "4", "season":"RS", "points": "89"}},
{"teamB": {"name": "BAR", "games": "3", "season":"RS", "points": "78"}}]
我平时读myfile.json
文件是这样的:
$mydata=file_get_contents("myjsonfiles/myfile.json");
$decodeddata = json_decode($mydata,true);
所以,我可以用它PHP。例如:
<?php
$teamApoints=$decodeddata["teamA"]["points"];
$teamBpoints=$decodeddata["teamB"]["points"];
$totalpoints=$teamApoints+$teamBpoints;
?>
<div class="apoints"><?php echo $teamApoints; ?></div>
<div class="bpoints"><?php echo $teamBpoints; ?></div>
<div class="totpoints"><?php echo $totalpoints; ?></div>
现在,问题所在。我对javascript功能非常新颖,我想使用myfile.json
文件的不断变化的信息来更新页面而不重新加载它。
一些网友给我的想法,但是,作为一个新人,这是我很难实现:
<head>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<script>
function updatePage() {
$.getJSON('myjsonfiles/myfile.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push("<li id='" + key + "'>" + val + "</li>");
});
jQuery("body").html("");
$("<ul/>", {
"class": "my-new-list",
html: items.join("")
}).appendTo("body");
});
}
setInterval(updatePage, 5000);
</script>
由于这是不正确的,我怎么能访问到myfile.json
内JS的元素函数并在PHP中使用它们?或者,如果这不可行,我如何访问myfile.json
文件的元素并替换div的内容?
感谢
的概念是:经过一段固定时间interval.Through此Ajax调用系统中读取您将创建一个AJAX调用JSON文件和显示结果在你的HTML(在这种情况下div)元素。 –
是的,但如何?你会告诉我如何读取json文件的单个元素(如我的例子)? – Javi