javascript - jQuery time display with AJAX requests -
i'm building webpage retrieves data server using ajax. i'm looking display time in div (in hours/minutes/seconds, 10:45:30, leading zeroes). 1 of ajax calls run infrequently; 45 minutes or between each call. call in question gets json string server's current time (via php). i'm able string hours, minutes, , seconds separated or 1 item.
i've seen lot of timer functions use setinterval
, js functions current time; these operate client-side/locally. i've seen functions ask server's time every minute (which seems frequent).
what grab server's time ajax call (which can assign variables; part have figured out)., , let timer function use variables call starting point increment seconds, minutes, etc.
here's idea of may like; first, ajax call gets time variables.
function asktime(){ $.ajax({ url: "servertime.php", datatype: "json", cache: false, success: function(data) { timehours = (data.timehours); timeminutes = (data.timeminutes); timeseconds = (data.timeseconds); timerfunction(); }, }); }
and on success of call, run function display time in div of id, $('#timedisplay).html(timestring)
.
so, shortly: how can use jquery display time using infrequent ajax calls server time?
gettime web method set on server side returns json encoded date time (something /date(milliseconds)/).
you might want change part of javascript (the first line in success callback) depending on how you date time web service.
var clienttimeupdater = null; function asktime() { $.ajax({ type: "post", url: "webform1.aspx/gettime", contenttype: "application/json; charset=utf-8", datatype: "json", success: function (msg) { var servernowgettime = msg.d.replace(/\/date\(/, '').replace(/\)\//, ''); var offset = (new date()).gettime() - servernowgettime; clearinterval(clienttimeupdater) // client side updater clienttimeupdater = setinterval(function () { var servernowgettime = new date((new date()) - offset); var hh = ('0' + servernowgettime.gethours()).slice(-2); var mm = ('0' + servernowgettime.getminutes()).slice(-2); var ss = ('0' + servernowgettime.getseconds()).slice(-2); $("#mytime").text(hh + ':' + mm + ':' + ss); }, 1000); } }); } $(document).ready(function () { // first call asktime(); // call every 45 minutes setinterval(asktime, 2700000); })
Comments
Post a Comment