2017-06-01 115 views
1

我有一個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的內容?

感謝

+0

的概念是:經過一段固定時間interval.Through此Ajax調用系統中讀取您將創建一個AJAX調用JSON文件和顯示結果在你的HTML(在這種情況下div)元素。 –

+0

是的,但如何?你會告訴我如何讀取json文件的單個元素(如我的例子)? – Javi

回答

1

請試試這個方法:

<html> 
<head> 
<script src="https://code.jquery.com/jquery-1.10.2.js"></script> 
</head> 
<script type="text/javascript"> 

    function updatePage() { 
    $.getJSON('myfile.json', function(data) { 
    var $string = ''; 
    var sum=0; 

    $.each(data, function(key, val) { 
     var x= Object.keys(val); 
     sum += parseInt(val[x]["points"]); 

     $string += "<div class='"+x+"'>"+x+" Points:" + val[x]["points"] + "</div>" ; 

    }); 
    $string += "<div class='totpoints'>Total Points:"+sum+"</div>" 
    jQuery("body").html($string); 
    }); 
} 
jQuery(document).ready(function() { 
    setInterval(updatePage, 1000); 
    //set your time as per requirement, so that after this time interval data will update automatically 
}); 

</script> 
<body></body> 
</html> 
+0

謝謝Dipanwita Kundu。我怎樣才能訪問json文件中的一個元素?我的意思是,在你的方法中,你爲「每一個」數據做了一些事情。但我想只讀取json文件的一個元素,例如val ['teamA'] ['points']。 – Javi

+0

我沒有讀過每個數據。數據檢查'teamA','teamB'obj。從那個obect我只獲取'points'。 console.log(數據)來獲取數據的值 –

+0

好的,你沒有達到每個數據,但你檢查每個'teamA,teamB'data。如果你只想達到'teamB''points''數據呢? – Javi