jquery函数里面的php代码来读取json文件

时间:2017-06-01 10:31:44

标签: php jquery json

我有一个myfile.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>

由于这是不正确的,我如何访问js函数内的myfile.json元素并在php中使用它们?或者,如果无法做到这一点,我怎样才能访问myfile.json文件的元素并替换div的内容?

由于

1 个答案:

答案 0 :(得分: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>