我有一個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