ajax+servlet 简易时间效果
<!DOCTYPE html> <html> <head> <title>index.html</title> <meta name="content-type" content="text/html; charset=UTF-8"> </head> <body> <h2 id="tt"></h2> <script> function i(id){ return document.getElementById(id); } var ajax=new XMLHttpRequest; ajax.onreadystatechange=ok; function ok(){ if(ajax.status==200&&ajax.readyState==4){ i('tt').innerHTML=ajax.responseText; } } function aa(){ ajax.open("post","timer"); ajax.send(null); } aa(); setInterval(aa,1000); </script> </body> </html>
package web11_ajax.servlet; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/timer") public class Timer extends HttpServlet{ /** * */ private static final long serialVersionUID = 1L; @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); String timer=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); PrintWriter out=response.getWriter(); out.print(timer); out.close(); } }