2017-05-29 163 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>