How can I get the web-server time开发者_高级运维 using jQuery?
Here's a way that may work without any particular code, or even a valid path, on the server side.
try {
var date = new Date($.ajax({'type': 'HEAD', 'url': '/'}).getResponseHeader('Date'));
}
catch(err) {
var date = null;
}
This is presumptive that the server will always return a "Date" header. Some experimentation with the particulars of your server will be necessary.
EDIT TO ADD: Note that this is more of a cutesy hackish way to do this. The "correct" way would be to set up a server-side script to return the server time quickly, or possibly put it inline to the page where the script will be running, or simply use the client-side time if it would be "good enough."
To get server code, you'll need to have some method on server-side that would either add time to the page while rendering, or if you need real-time time (ops), you need to make an ajax call to server using jQuery. That means that you need to have something on server side that would respond to ajax request. What language are you using for server side?
If you've got something like php running on your server you could just put something like this to set the date/time by embedding it into the script:
<script>
var date = new Date("<?php echo date("Y-m-d H:i:s"); ?>");
alert(date);
</script>
used Garrett answer, but $.ajax has a short response time, which means its 'getResponseHeader' method cannot be called immediately.
I think this can be a fix:
var Date1 = null;
var endInterval;
function DoJob() {
if (Date1 == null) {
if (endInterval)
clearInterval(endInterval);
endInterval = setInterval(DoJob, 100);
return;
}
/*
job to do...
*/
if (endInterval)
clearInterval(endInterval);
}
try {
var oHead = $.ajax({ 'type': 'HEAD', 'url': '/' }).success(function () {
Date1 = new Date(oHead.getResponseHeader('Date'));
});
}
catch (err) {
Date1 = null;
}
DoJob();
精彩评论