AJAX基础(一)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/erchouchou/article/details/81459477

获取当前时间

不需要去刷新整个页面,只需要局部刷新

jsp界面代码:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>Ajax Demo</title>
    <meta charset = "utf-8">
  </head>
      
  <body>
     时间:<span id = "spanID"></span><br>
  <%-- <form action="${pageContext.request.contextPath}/timeServlet" method="GET">
      <input type="submit" value="提交">
  </form> --%>
  <input type="button" value="提交" id = "buttonID">
  <script type="text/javascript">
      function createAJAX(){
      var ajax = null;
      try{
         ajax = new ActiveXObject("microsoft.xmlhttp");
      }catch(e1){
         ajax = new XMLHttpRequest();
      }
       return ajax;
      }
  </script>
  
  <script type="text/javascript">
  document.getElementById("buttonID").onclick = function(){
   //1.创建ajax对象
   var ajax = createAJAX();
   //2.准备发送请求
   var method = "GET";
   var url = "${pageContext.request.contextPath}/timeServlet";
   ajax.open(method, url);
   //3.发送请求(发送请求体到服务器,无数据就用null)
   ajax.send(null);
   //4.ajax异步对象 监听服务器响应状态
   //相应状态为0-1-2-3-4,状态变化才触发function函数
   ajax.onreadystatechange = function(){
      if(ajax.readyState == 4){
        if(ajax.status==200){
          //5.从ajax中获取服务端数据
          var timeStr = ajax.responseText;
          document.getElementById("spanID").innerHTML = timeStr.fontcolor("red");
        }
      }
   }
   //----------
   
  }
  </script>
  <br/><br/><br/>
  静态文本静态文本<br/>
  静态文本静态文本<br/>
  静态文本静态文本
  </body>
</html>

servlet代码:

package Ajax;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class timeServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/DD hh:dd:ss");
        String timeStr = format.format(new Date());
        //request.setAttribute("timeStr", timeStr);
        PrintWriter writer = response.getWriter();
        writer.write(timeStr);
        writer.flush();
        writer.close();
	}
}

 

阅读更多
换一批

没有更多推荐了,返回首页