How can you make or can someone saw the source code of the ready solution. The situation is the following, the server time Moscow time is shown on the site: <? = Date ("H")?> : <? = Date ("i");?>

How can you do this on Ajax, as follows. The user visits the page, a request is sent to show the time, and there is no more request. Further the javascript itself adds seconds and changes time?

  • and what exactly you can not? The logic is simple, $ .post (URL, function (data) {var time = data}); further setTimeOut (); adds +1 to seconds every 1000ms and form the clock. - Fucking Babai
  • Could you write more fully? i'm not a js connoisseur - Tchort

3 answers 3

Let's use the @DemoS example

The server must have a script sent by the server time:

time.php:

<?php $servTime=Array(); //$this_time=time(); $servTime['currentYear']=date("Y"); $servTime['currentMonth']=date("n"); $servTime['currentDate']=date("j"); $servTime['currentDay']=date("N"); $servTime['currentHours']=date("G"); $servTime['currentMinutes']=date("i"); $servTime['currentSeconds']=date("s"); echo encode_json($servTime); ?> 

Next, we use the @DemoS functions to be redesigned so that they do not contact the server every second, but adding 1 to seconds will generate minutes and hours (here you will have to think out).

 $(document).ready(function(){ var objTime; $.getJSON("time.php", function(data){ objTime=$.parseJSON(data); }); }); 

objTime will be a time object. objTime.currentYear - will correspond to the year and so on.

Next we pass the objTime object to the clock () function;

    Here is my implementation, only the client’s time goes right away, but I think it’s not a problem to undermine: date and time (jQuery)

      If absolute accuracy is not extremely important, it can be made much simpler:


      var serverDate; function timeStart () { timestamp = document.getElementById ("moscowTime"). innerHTML; serverDate = parseInt (timestamp) * 1000; setInterval ("showTime ()", 1000); } function showTime () { serverDate = serverDate + 1000; date = new Date (serverDate); var time = date.getHours () + ":" + date.getMinutes () + ":" + date.getSeconds (); var timeWrapper = document.getElementById ("moscowTime"); timeWrapper.innerHTML = time; } onload = function () { timeStart (); }

       <div id="moscowTime"><?=time();?></div> 

      PS: it is written without Ajax. laid out strictly the algorithm, of course, the accuracy will be higher if you take the timestamp Ajax on onload.