1

時間値を含む2つの変数を比較したいのですが、1つはページの作成時に生成され、もう1つはデータベースから取得されます。また、ページが作成されたときに開始し、データベースの時刻を受信するとアラートを表示するタイマーを作成したいと思います。

jQueryでこれら2つのタスクを実行するためにどのようなソリューションを提案しますか?

1)jQueryを使用してデータベースの時間値を取得するにはどうすればよいですか?
2)ページが作成されたときに開始するタイマーを作成するにはどうすればよいですか?

4

1 に答える 1

0

Let's make some assumptions

  • your server-side scripting language is php
  • your time value is a Unix simestamp (seconds since 1 January 1970)
  • jQuery is installed on the page (your question is tagged jQuery).

First, serve your page with the database time value in a suitable HTML container:

<?php
//retrieve value from database here.
$dbTimeValue = ......;
?>

<body>
...
<input type="hidden" id="dbTimeValue" value="<?php echo $dbTimeValue ?>" />
...
</body>

Then, client-side, in javascript:

$(function() {
    var dbTimeVal = Number( $("#dbTimeValue").val() ) * 1000;//Unix timestamp converted to milliseconds
    var timeNow = (new Date()).getTime();//time now (from client computer's motherboard) expressed in milliseconds since 1 Jan 1970
    var timeOut = setTimeout(function() {
        alert("Time now is later than database time");
    }, timeNow - dbTimeVal);
});

Note: The database time value could be served directly into javascript with var dbTimeVal = <?php echo $dbTimeValue ?>; but this is arguably more confusing to a noob.

于 2012-04-14T11:50:16.680 に答える