x php函数的JS函数相同

时间:2013-11-18 11:54:29

标签: javascript php jquery ajax timer

我的php页面上有X表。在每一个,我都是计时器。这些计时器的持续时间不同。我想知道如何使用一个JS / AJAX函数刷新这些计时器(分离)。

timer.php(我不能发布真实的代码,只是一个让你理解的例子)

<?php
  tab_number = X;
  for ($i=0; $i<=X; $i++) {
  $duration = MySQL query on duration with $i parameter. Return seconds for the timer.
  $time_left = php function to change seconds to min:sec and to decrease $time_left each seconds

// just keep in mind that my timer is working, all of above is an example, my problem is on refresh.

echo '<table>';
  echo '<tr>';
    echo '<td><div id="rem_time'.$i.'">' . $time_left. ' left</div></td>';
  echo '<tr>';
echo '<table>';

同一页面上的javascript功能:

<script type="text/javascript">
  function refresh() {
    $('#rem_time').load('time.php #rem_time');
  }
  setInterval('refresh()',1000);
</script>

我想知道是否可以为每个rem_time1,rem_time2,...,rem_timeX分别使用我的JS脚本

2 个答案:

答案 0 :(得分:0)

您可以在每个表上使用数据属性,并使用您的ajax调用查询php脚本。以下是使用两个具有不同计时器计数的表的示例:

<强> HTML

<div id="table1" class="container">
    <table data-url="/path/to/script.php?table=1" data-timer="1000">
        <!-- Table content -->
    </table>
</div>

<div id="table2" class="container">
    <table data-url="/path/to/script.php?table=2" data-timer="500">
        <!-- Table content -->
    </table>
</div>

<强> JAVASCRIPT

// Here we select using the attribute, you could use a class or other
$('[data-timer]').each(function(){
    $this = $(this);
    $parent = $this.parents('div.container');

    // Set interval will call the load function every x milliseconds
    setInterval(function(){
        // Now we use the table data attributes to load the
        // correct data with the correct inteval
        $parent.load( $this.attr('data-url'), function() {
            console.log( "Load was performed." );
        });
    }, $this.attr('data-timer') );
});

<强> PHP

$table = $_GET['table']

if($table == '1'){
    // ouput table 1 html
}else{
   // output table 2 html
}

答案 1 :(得分:0)

我改变了我的代码:

<强> JAVASCRIPT

function timer(i, start_date, duration) {
    setInterval(function() {
        var date_now = Math.round(new Date().getTime() / 1000);
        var rem_time = duration - (date_now - start_date);

        // Times calculs
        minuts = parseInt(rem_time / 60);
        seconds = parseInt(rem_time % 60);

        if (rem_time >= 0)
            document.getElementById("rem_time"+i).innerHTML = minuts + ":" + seconds;
    }, 1000);
}

PHP / HTML(混合但语法错误)

<table>
    for ($i=1; $i<X; $i++) {
        <tr><td>
            <div id="rem_time".$i.> <script> timer($i, '14:30:25', 600);</script></div>
        </tr></td>
    }
</table>

它有效:)

全部!