0

我有一个从 1 小时倒计时到零的计时器。当它达到零时,jQuery 会触发一个事件(代码如下)。

我需要将数据库表更新为当前的-1。(所以比如表格的数值设置为20,倒计时到零后变成19,以此类推)。

我的问题是 - 如何基于 jQuery 函数以这种方式更新 MySQL 数据库?我曾尝试使用 PHP,但它会立即更新表格,而不是在倒计时达到零时。(我已经尝试过搜索这个,现在我意识到 PHP 是服务器端,而 jQuery 是客户端,但我仍然不知道如何让这样的事情工作)。

非常感谢您的帮助!

  <script type="text/javascript">



var year=2012;        //Set initial values for timer
var month=06;          
var day=16;           
var hour=17;          
var minute=10;        
var tz=+12;            


var montharray=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");

function countdown(yr,m,d,hr,min){
    theyear=yr;themonth=m;theday=d;thehour=hr;theminute=min;
    var today=new Date();
    var todayy=today.getYear();
    if (todayy < 1000) {
    todayy+=1900; }
    var todaym=today.getMonth();
    var todayd=today.getDate();
    var todayh=today.getHours();
    var todaymin=today.getMinutes();
    var todaysec=today.getSeconds();
    var todaystring1=montharray[todaym]+" "+todayd+", "+todayy+" "+todayh+":"+todaymin+":"+todaysec;
    var todaystring=Date.parse(todaystring1)+(tz*1000*60*60);
    var futurestring1=(montharray[m-1]+" "+d+", "+yr+" "+hr+":"+min);
    var futurestring=Date.parse(futurestring1)-(today.getTimezoneOffset()*(1000*60));
    var dd=futurestring-todaystring;
  //  var dday=Math.floor(dd/(60*60*1000*24)*1);
    var dhour=Math.floor((dd%(60*60*1000*24))/(60*60*1000)*1);
    var dmin=Math.floor(((dd%(60*60*1000*24))%(60*60*1000))/(60*1000)*1);
    var dsec=Math.floor((((dd%(60*60*1000*24))%(60*60*1000))%(60*1000))/1000*1);
    if(dhour<=0&&dmin<=0&&dsec<=0){

      //--TIMER REACHES ZERO HERE. Code needed to update MySQL would go here?

    }
    else {
        document.getElementById('count2').style.display="none";
      // document.getElementById('dday').innerHTML=dday;
        document.getElementById('dhour').innerHTML=dhour;
        document.getElementById('dmin').innerHTML=dmin;
        document.getElementById('dsec').innerHTML=dsec;
        setTimeout("countdown(theyear,themonth,theday,thehour,theminute)",1000);
    }
}
</script>

PS。这是我尝试用来更新我的数据库表的 PHP 代码:

<?php
        include("db.php");
        mysql_select_db("myData") or die(mysql_error());
        mysql_query("UPDATE cards SET buy=0.01 WHERE id='67'") or die(mysql_error());
        ?>
4

1 回答 1

0
You have to use $.ajax ([http://api.jquery.com/jQuery.ajax/][1]) to do it because jQuery alone do not have access to the database on the server.
In your javascript code inside the if :     

if(dhour<=0&&dmin<=0&&dsec<=0){

      //--TIMER REACHES ZERO HERE. Code needed to update MySQL would go here?

      $.ajax({ 
          url: "pathToYourPHPUpdateScript.php",
          type: "POST",
          success: function(){
            alert("MYSQL UPDATED!");
          }
      });

    }
于 2012-06-16T08:19:57.483 回答