2017-05-29 64 views
0

我正在为我们当地的足球俱乐部构建一个窄播解决方案。在其中一个网页上,我想循环播放这些小组而不用重新加载。团队数据是通过数据属性获取的。它看起来像这样:通过数据阵列循环

$teamcode = 'seniors1'; 
$poulecode = 'A'; 
$teamdata = ' 
<div id="teamcontainer"> 
<div data-param-poulecode="'.$poulecode.'"></div> 
<div data-param-teamcode="'.$teamcode.'"></div> 
</div> 
'; 
echo $teamdata 

有多个团队和多个poules。有没有办法循环访问teamdata数组,每隔10秒用新的团队变量刷新teamcontainer,而不重新加载页面?

+0

ID必须是唯一的 – Andreas

+1

据我所知,循环将在服务器,而不是在客户端。对?关于刷新,如果你想从服务器获取数据**使用['ajax'](https://www.w3schools.com/xml/ajax_intro.asp)(强烈建议使用[jQuery](http ://api.jquery.com/jquery.ajax/)如果你没有很多项目,那么从服务器返回一次,然后在客户端使用javascript进行操作。 –

回答

0

您可以将data-param-attributes设置为使用php的数据数组。然后使用jquery迭代数据并更改值。这里有一个例子:

<?php 
// Save codes as array 
$teamcode = ['seniors1','seniors2']; 
$poulecode = ['A','B']; 
$teams = json_encode($teamcode); 
$poules = json_encode($poulecode); 
?> 
<!DOCTYPE html> 
<html> 
<head> 
    <script type= "text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
</head> 
<body> 
    <div id="teamcontainer"> 
     <!--pass variables into data-param attribute--> 
     <div id="teams" data-param-teamcode='<?php echo $teams; ?>'></div> 
     <div id="poules" data-param-poulecode='<?php echo $poules; ?>'></div> 
    </div> 
</body> 
<script type="text/javascript"> 
    $(document).ready(function(){ 
     var teams = $("#teams").data("paramTeamcode"), poules = $("#poules").data("paramPoulecode"); 
     var activeTeamIndex = 0, activePouleIndex = 0; 

     // Switch teams and poles 
     var switchTeams = function(activeIndex){ 
      $("#teams").text(teams[activeIndex]); 
     }; 
     var switchPoules = function(activeIndex){ 
      $("#poules").text(poules[activeIndex]); 
     }; 

     // Show the first teams and poules 
     switchTeams(0); 
     switchPoules(0); 

     // Switch teams and poles every 10 seconds 
     setInterval(function(){ 
      // Reset indexes if they exceed array length 
      if (activePouleIndex > poules.length) 
       activePouleIndex = 0; 
      if (activeTeamIndex > teams.length) 
       activeTeamIndex = 0; 
      switchTeams(activeTeamIndex++); 
      switchPoules(activePouleIndex++); 
     },10000); 
    }); 
</script> 
</html>