Home >Web Front-end >JS Tutorial >Javascript implementation to obtain server time_javascript skills
JS is a script that runs on the client, not on the server. Generally speaking, when getting the time through JS, the time obtained is the time on the visitor’s local computer. In order to prevent the time on the web page from changing due to the visitor Depending on the computer, we need to get the server time directly through JS.
The following is the complete js code to get the server time. It is a complete example of using javascript to get the server time. js dynamically refreshes the server time.
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>AJAX获取服务器时间</title> <script type="text/javascript"> /* * ajax 函数,处理 ajax 请求 * @param function callback 回调函数 * @因为要和服务器交互,所以必须在服务器环境运行,不能在硬盘上直接打开 */ function ajax(callback){ if(typeof callback!='function') return; var ajaxObject; try{ ajaxObject=new XMLHttpRequest(); }catch(e){ try{ ajaxObject=new ActiveXObject('Microsoft.XMLHTTP'); }catch(e){ } } if(!ajaxObject) return; if(ajaxObject.overrideMimeType){ ajaxObject.overrideMimeType('text/html'); } //location.href可以换成其他url,但必须是同一个站点的链接,并且文件存在 ajaxObject.open('get',location.href); ajaxObject.send(null); ajaxObject.onreadystatechange=function(){ if(ajaxObject.readyState==4){ if(ajaxObject.status==200){ callback(ajaxObject); } } }; } /* * 获取时间并动态刷新 */ function getTime(){ ajax( function(ao){ //只需要AJAX一次,将服务器时间获取后以毫米为单位保存到一个变量中 _timestamp=Date.parse(ao.getResponseHeader('Date')); _timestamp=_timestamp.toString().match(/^\d$/)?_timestamp:new Date().getTime(); //设置定时器每过一秒动态刷新一次时间 setInterval( function(){ //这里可以自定义时间显示格式 document.getElementById('_timer').innerHTML=new Date(_timestamp).toLocaleString(); _timestamp+=1000; }, 1000 ); } ); } window.onload=getTime; </script> </head> <body> <div id="_timer">正在获取服务器时间……</div> </body> </html>
Think analysis:
The concept of server-side time is very vague. Because the server side may not be composed of one machine after all. In the simplest case, it is also divided into web server and db server. Which one are you talking about
If it is a web server.
Then just use new Date() directly in java or .net
Do not add new Date in the 3f1c4e4b6b16bbbd69b2ee476dc4f83a on the web page, that is just the client time
If it is a db server.
Need to connect to the database and obtain it through sql. For example, Oracle's select sysdate from dual.
Example:
If js wants to obtain such server-side time, there are many methods. The idea is roughly the same.
1.
4ec11beb6c39d0703d1751d203c17053
var date = 7da3b65d188703abd1a1712558c7dff6
2cacc6d41bbb37262a98f745aa00fbf0
2.bba8f8188f9e1e1551427ba38711a9422cacc6d41bbb37262a98f745aa00fbf0
Write the Servlet's return stream into a js file so that var nowDate = server-side time
3.ajax, I won’t talk about this, there are a lot of them on the Internet
The above is the entire content of this article, I hope you all like it.