Use JS to do time correction, get the local time, there is a bug.
The use of JS can also get to the server time, the principle is to use the AJAX request, the header information returned contains the server-side time information, get to it. Following:
1. Rely on jquery
Code:
function getserverdate () { returnnewfalse}). getResponseHeader ("Date"));
The above function returns a Date object that must be synchronized when using Ajax, or the time date cannot be returned.
No need to fill out the request link;
If the server time and local time are sometimes poor, you need to make corrections.
2. Native
Code:
functiongetserverdate () {varXHR =NULL; if(window. XMLHttpRequest) {XHR=Newwindow. XMLHttpRequest (); }Else{//IEXHR =NewActiveobject ("Microsoft")} xhr.open ("GET", "/",false)//false immutable Xhr.send (NULL); varDate = Xhr.getresponseheader ("date"); return Newdate (date);}
Also returned is a Date object, Xhr.open () must use synchronization;
No need to fill out the request link; open,send, and getResponseHeader must be written sequentially.
To use asynchronous requests, you can listen to the onreadystatechange state to do different things.
The code is as follows:
functiongetserverdate () {varXHR =NULL; if(window. XMLHttpRequest) {XHR=Newwindow. XMLHttpRequest (); }Else{//IEXHR =NewActiveobject ("Microsoft")} xhr.open ("GET", "/",true); Xhr.send (NULL); Xhr.onreadystatechange=function(){ vartime,date; if(Xhr.readystate = = 2) { time= Xhr.getresponseheader ("Date"); Date=NewDate (time); Console.log (date); } }}
Using Async is not a convenient time to return.
There are four kinds of readystate, which are convenient for different treatments:
- 0: Request not initialized
- 1: Server Connection established
- 2: Request received
- 3: In Request processing
- 4: The request is complete and the response is ready
Failed state, status value:
$: "OK"
404: Page Not Found
JS how to get server-side time?