JSP页面: <%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%> <%@tagliburi="http://java.sun.com/jsp/jstl/core"prefix="c"%> <!DOCTYPEHTMLPUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>AJAX异步请求</title> <Metahttp-equiv="pragma"content="no-cache"> <Metahttp-equiv="cache-control"content="no-cache"> <Metahttp-equiv="expires"content="0"> <!-- <linkrel="stylesheet" type="text/css"href="styles.css"> --> <scripttype="text/javascript"> window.onload =function(){ //异步请求 document.getElementById("btn").onclick = function(){ //ajax开发步骤 //1、创建一个异步对象 //低版本IE(6.0或以前)或IE高版本: ActiveXObject对象 //火狐或IE高版本(7.0或以上): XMLHttpRequest对象 varajax; try{ ajax =newXMLHttpRequest(); }catch(e){ ajax =newActiveXObject("microsoft.xmlhttp"); } //2、准备请求,打开请求 //url:请求地址 //method:提交方式:get和post varurl ="<c:url value='/getTime'/>"; varmethod="GET"; ajax.open(method,url); //3、设置并发送的请求内容(正文) //如果是GET一般为null,POST才需要指定的请求正文 ajax.send(null); //4、先监听服务器的返回状态,只有状态ok的请求才回处理 ajax.onreadystatechange =function(){ //alert("服务器请求的状态:"+ajax.readyState); //alert("服务器响应的状态:"+ajax.status); if(ajax.readyState==4 && ajax.status==200){ //5.接收服务器的数据 varcurTime = ajax.responseText; //网页局部刷新 document.getElementById("time").innerHTML = curTime; } } alert(ajax); } } </script> </head> <body> <inputid="btn"type="button"name="btn"value="异步请求"/> <br> <spanid="time"></span><br> <inputtype="text"/> </body> </html>
@H_301_4@
创建一个Servlet,在web.xml配置好访问路径 package star.july.ajax; import java.io.IOException; 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; publicclass getTimeServlet extends HttpServlet { @Override protectedvoid doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { Date curTime= new Date(); //格式化日期 SimpleDateFormat sf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String format= sf.format(curTime); //设置页面编码 response.setContentType("text/html;charset=utf-8"); //传递数据回页面 response.getWriter().write("现在时间是:"+format); } @Override protectedvoid doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException { doGet(req,resp); } }@H_301_4@