douhaodang0403 2015-02-08 13:47
浏览 39
已采纳

javascript倒计时和更新数据库php

I would like to implement a JavaScript code to count down hundred seconds. I have written the code for count down, but I need the value of the remaining time and update it in a database on every second. Below is an example of what I would like to accomplish:

On Every second I would like to run:

UPDATE 'table' SET 'timeleft=[remaining time]'

Is this possible?

Below is what I've tried so far:

<? $time = "100"; ?>

<script>
var intCountDown = <?php echo $time; ?>;

function countDown()
{
    if(intCountDown < 0)
    {
        cntdwn.innerText = 'Done';
        return;
    }

    cntdwn.innerText = intCountDown--;

    setTimeout("countDown()",1000);
}
</script>

Then just: <div id=cntdwn></div>

Additionally this may help clarify my intention: I want to implement a single-shot timer but prefer the counter to overflow back to where it started after the page refresh.

  • 写回答

1条回答 默认 最新

  • drwo2014 2015-02-08 14:24
    关注

    To do that, you'll need AJAX:

    here is your AJAX function:

    function loadXMLDoc(timeleft)
    {
    var xmlhttp;
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        cntdwn.innerHTML=xmlhttp.responseText;
        }
      }
    xmlhttp.open("GET","update.php?timeleft="+timeleft,true);
    xmlhttp.send();
    }
    

    Using above function, we can send an int to update.php?timeleft= and update.php should connect to database and update your timeleft value (i think you wrote it anyway). and in your countdown function just replace this line:

    cntdwn.innerText = intCountDown--;
    

    with this(since we will update innerText in ajax call):

    intCountDown--;
    

    that's all needs to be done

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能