dse55384
2013-06-05 01:25
浏览 376
已采纳

javascript倒计时更新db并刷新

can someone please help me with js/ajax countdown i want a countdown timer to 10 sec then update the database and refresh the page once it hits to 0.

i'm not really good with javascript/ajax, here is what i got so far:

var ss = 10;
function countdown() {
ss = ss-1;
if (ss<0) {
var url='update.php?countdown='+countdown;
}
else {
document.getElementById("countdown").innerHTML=ss;
window.setTimeout("countdown()", 1000);
}
}

<span id="countdown" style="color:green;">10</span>

and update.php file, witch works fine:

if (isset($_REQUEST['countdown'])) {     
  mysql_query("INSERT INTO num (id, ad, active) 
  VALUES ('1', 'Test',1)") or die(mysql_error());
  }

and also this is what i found http://pastebin.com/Qwz3Zqtt , works fine but i don't know how to put them together.

any helps would be appreciated.

Thanks

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doujing4555 2013-06-05 01:57
    已采纳

    You're going to want to learn basic ajax to process the database request. jQuery has a very easy to use implementation.

    The basic code could be something like:

    <script>
    function updateTimer(seconds){
        var countdown = document.getElementById('countdown');
        countdown.innerHTML = "Please wait " + seconds + " seconds.";
    }
    
    var timer = function() {
        var seconds = 10;
        var interval = setInterval(function(){
            if (seconds <= 0){
                countdown.innerHTML = "Finished.. Updating Database";
                // AJAX request here
                clearInterval(interval);
            }else{
                updateTimer(seconds);            
                --seconds;
            }
        }, 1000);
        updateTimer(seconds);    
        --seconds;
    }
    
    document.getElementById('start').addEventListener('click', timer);
    </script>
    
    <div id="countdown"></div>
    <button id="start">Click Me</button>
    

    Here's a fiddle

    评论
    解决 无用
    打赏 举报
  • 查看更多回答(1条)

相关推荐 更多相似问题