ホームページ  >  記事  >  ウェブフロントエンド  >  HTML はどのようにしてサーバーの時刻を返すのでしょうか? _html/css_WEB-ITnose

HTML はどのようにしてサーバーの時刻を返すのでしょうか? _html/css_WEB-ITnose

WBOY
WBOYオリジナル
2016-06-24 11:32:241412ブラウズ

HTML はどのようにしてサーバーの時刻を返すのでしょうか?返される時刻の形式は 2015-12-01 11:11:11 です。


ディスカッションへの返信(解決策)

取得する方法はなく、バックグラウンドページでのみ出力できます

バックグラウンドから取得した後、に渡しますフロント。 。 。

バックグラウンドから受け取ったら、フロントにお渡しください。 。 。


関連するコードを探しています

ローカル時間を取得するコードは次のとおりです。サーバー時間を取得するように変更できますか?

          function getTime(){                var today = new Date();                 var year = today.getFullYear();                 var month = today.getMonth() + 1;                 var day = today.getDate();                 var hours = today.getHours();                 var minutes = today.getMinutes();                 var seconds = today.getSeconds();                 if(month < 10){                     month = "0" + month;                }                if(day < 10){                     day = "0" + day;                }                if(hours < 10){                    hours = "0" + hours;                }                if(minutes < 10){                     minutes = "0" + minutes;                }                if(seconds < 10){                    seconds = "0" + seconds;                }                var time = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;                          document.getElementById("currentTime").innerHTML = time;                setTimeout("getTime()",1000);              }

バックグラウンドはインターフェースを提供しており、ajax を使用してインターフェースからサーバー時刻を取得できます。 例は次のとおりです。
$.get("data.php",null,function(data){
document. getElementById("currentTime").innerHTML = data.time
);

フロントに背景を渡す

詳細を聞きたい


最近、テクノロジーを推し進めます。なぜだめですか。 sse または websocket を使用できます Java サーブレットの例:

環境 tomcat7 && java7 && servlet3.01

javascript:

<script type="text/javascript">function sseHandler(){    if(typeof(EventSource)!="undefined"){        var source=new EventSource("time");        source.onopen = function(event) {            console.log("sse opened!");        };        source.onmessage=function(event){                console.log(event.data);        };    }else{         console.log("HTML5 not supported");    }}window.addEventListener("load", sseHandler);</script>


非同期サーブレット: TimeServiceServlet
import java.io.IOException;import java.util.concurrent.ScheduledThreadPoolExecutor;import javax.servlet.AsyncContext;import javax.servlet.AsyncEvent;import javax.servlet.AsyncListener;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * Servlet implementation class TimeServiceServlet */@WebServlet(urlPatterns = {"/time"}, asyncSupported = true)public class TimeServiceServlet extends HttpServlet {	private static final long serialVersionUID = 1L;	//private final Queue<AsyncContext> ongoingRequests = new ConcurrentLinkedQueue<>();    /**     * @see HttpServlet#HttpServlet()     */    public TimeServiceServlet() {        super();        // TODO Auto-generated constructor stub    }	/**	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)	 */	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		// TODO Auto-generated method stub		request.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);		response.setContentType("text/event-stream");		response.setCharacterEncoding("UTF-8");		final AsyncContext ac = request.startAsync();		ac.setTimeout(1*1000);		ac.addListener(new AsyncListener() {		      @Override public void onComplete(AsyncEvent event) throws IOException {		    	  System.out.println("@c");		      }		      @Override public void onTimeout(AsyncEvent event) throws IOException {		    	  System.out.println("@t");		      }		      @Override public void onError(AsyncEvent event) throws IOException {		    	  System.out.println("@e");		      }		      @Override public void onStartAsync(AsyncEvent event) throws IOException {		    	  System.out.println("@s");		      }		});	    ScheduledThreadPoolExecutor ec=new ScheduledThreadPoolExecutor(10);	    ec.execute(new AsyncTimeService(ac));	}}

実行可能な実装クラス: AsyncTimeService日付文字列を出力
import java.io.IOException;import java.io.PrintWriter;import java.text.SimpleDateFormat;import java.util.Date;import javax.servlet.AsyncContext;public class AsyncTimeService implements Runnable {	AsyncContext ac;		public AsyncTimeService(AsyncContext ac) {		super();		this.ac = ac;	}	@Override	public void run() {		// TODO Auto-generated method stub		Date now=new Date();		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");				try {			PrintWriter out = ac.getResponse().getWriter();			out.write("data:"+sdf.format(now)+ "\n\n");		} catch (IOException e) {			// TODO Auto-generated catch block			e.printStackTrace();		}finally{			ac.complete();		}	}}





Java サーブレットの例:

環境 tomcat7 && java7 && servlet3.01

javascript:

<script type="text/javascript">function sseHandler(){    if(typeof(EventSource)!="undefined"){        var source=new EventSource("time");        source.onopen = function(event) {            console.log("sse opened!");        };        source.onmessage=function(event){                console.log(event.data);        };    }else{         console.log("HTML5 not supported");    }}window.addEventListener("load", sseHandler);</script>


非同期サーブレット: TimeServiceServlet
import java.io.IOException;import java.util.concurrent.ScheduledThreadPoolExecutor;import javax.servlet.AsyncContext;import javax.servlet.AsyncEvent;import javax.servlet.AsyncListener;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * Servlet implementation class TimeServiceServlet */@WebServlet(urlPatterns = {"/time"}, asyncSupported = true)public class TimeServiceServlet extends HttpServlet {	private static final long serialVersionUID = 1L;	//private final Queue<AsyncContext> ongoingRequests = new ConcurrentLinkedQueue<>();    /**     * @see HttpServlet#HttpServlet()     */    public TimeServiceServlet() {        super();        // TODO Auto-generated constructor stub    }	/**	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)	 */	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		// TODO Auto-generated method stub		request.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);		response.setContentType("text/event-stream");		response.setCharacterEncoding("UTF-8");		final AsyncContext ac = request.startAsync();		ac.setTimeout(1*1000);		ac.addListener(new AsyncListener() {		      @Override public void onComplete(AsyncEvent event) throws IOException {		    	  System.out.println("@c");		      }		      @Override public void onTimeout(AsyncEvent event) throws IOException {		    	  System.out.println("@t");		      }		      @Override public void onError(AsyncEvent event) throws IOException {		    	  System.out.println("@e");		      }		      @Override public void onStartAsync(AsyncEvent event) throws IOException {		    	  System.out.println("@s");		      }		});	    ScheduledThreadPoolExecutor ec=new ScheduledThreadPoolExecutor(10);	    ec.execute(new AsyncTimeService(ac));	}}

実行可能な実装クラス: AsyncTimeService、使用日付文字列
import java.io.IOException;import java.io.PrintWriter;import java.text.SimpleDateFormat;import java.util.Date;import javax.servlet.AsyncContext;public class AsyncTimeService implements Runnable {	AsyncContext ac;		public AsyncTimeService(AsyncContext ac) {		super();		this.ac = ac;	}	@Override	public void run() {		// TODO Auto-generated method stub		Date now=new Date();		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");				try {			PrintWriter out = ac.getResponse().getWriter();			out.write("data:"+sdf.format(now)+ "\n\n");		} catch (IOException e) {			// TODO Auto-generated catch block			e.printStackTrace();		}finally{			ac.complete();		}	}}

この段落 コードは非常に高度なので、今後ゆっくり勉強していきます。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。