Ajax技术概要
1.Ajax原理
Ajax即Asynchronous JavaScript and XML,异步Javascript和XML.
Ajax不是一种新的技术,而是几种已有技术的整合,它采用XMLHttpRequest对象进行数据的异步交互,使用javascript增强用户体验,使用DOM组织内容,CSS显示外观,使用XML封装数据。
Ajax的创新点在于,无须刷新页面即可更新页面的部分内容,而传统方式页面内容改变时必须刷新整个页面。应用Ajax技术的包括Google Maps,Gmail,Youtube,and Facebook tabs.
重点需要掌握的概念:
同步机制:传统的Web交互中,首先用户通过界面触发一个HTTP请求到服务器,服务器根据请求内容进行相应的处理,然后将处理完毕的内容再返回给客户端,这是一个同步的过程,当服务器处理客户端提交的请求时,客户端的用户只能空闲等待,无论用户是想处理很少的数据,还是要进行大批量的数据处理,服务器都会给用户返回一个完整的页面。
异步机制:Ajax采取异步机制,使得用户可以一边等待反应,以便查看网页中的内容。Ajax的工作原理相当于在用户和服务器之间加了一个引擎,这个引擎用来统一处理提交的数据,它把不需要服务器端处理的数据直接返回给页面,而只把需要后台处理的数据发送给服务器端。在这种异步交互下,客户端不需要重新读取整个页面,而只读取需要的那部分内容,带来了更好的用户体验。
Ajax工作原理如下图(来自:http://www.w3schools.com/ajax/ajax_intro.asp)所示:
下面通过获取时间信息的传统处理方式和利用Ajax的异步方式的示例,来增加理解。
示例1-1传统Web方式
timeMsgOld.jsp
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <%@ page import="java.sql.*,java.util.*,javax.servlet.*" %>
- <%
- //获取服务器传来的数据
- String msg = (String)((request.getAttribute("msg")==null)
- ?"":(String)request.getAttribute("msg"));
- %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <Meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>传统的Web开发方式</title>
- </head>
- <body>
- <form action="/ServletDemos/timeMsgOld.do" method="get">
- <span id="msg"><%=msg %></span>
- <input type = "submit" value="单击此按钮">
- </form>
- </body>
- </html>
TimeMsgOld.java
- package com.wangdq;
- import java.io.IOException;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import javax.servlet.RequestDispatcher;
- 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,TimeMsgOld
- */
- @WebServlet("/timeMsgOld.do")
- public class TimeMsgOld extends HttpServlet {
- private static final long serialVersionUID = 1L;
- public TimeMsgOld() {
- super();
- // TODO Auto-generated constructor stub
- }
- protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
- // TODO Auto-generated method stub
- response.setContentType("text/plain;charset=UTF-8");
- request.setAttribute("msg","现在时间是: "+getCurrentDateAndTime()+" 欢迎您!");
- RequestDispatcher rd = request.getRequestDispatcher("/timeMsgOld.jsp");
- rd.forward(request,response);
- }
- /**
- * 获取当前系统时间
- */
- private String getCurrentDateAndTime() {
- String currentDate = "";
- SimpleDateFormat sdf = new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
- currentDate = sdf.format(new Date( ));
- return currentDate;
- }
- protected void doPost(HttpServletRequest request,IOException {
- // TODO Auto-generated method stub
- this.doGet(request,response);
- }
- }
执行结果如下:
示例1-2Ajax异步刷新
timeMsg.jsp
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <Meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>Ajax</title>
- <script type="text/javascript">
- function ok() {
- var xmlhttp;
- if(window.XMLHttpRequest) {
- // code for IE7+,Firefox,Chrome,Opera,Safari
- xmlhttp = new XMLHttpRequest();
- }else if(window.ActiveXOjbect) {
- // code for IE6,IE5
- xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
- }
- //设定回调函数,当数据返回时系统会执行这个回调函数
- xmlhttp.onreadystatechange = function() {
- if(xmlhttp.readyState==4 && xmlhttp.status==200) {
- document.getElementById("msg").innerHTML = xmlhttp.responseText ;
- }
- }
- //设定请求
- xmlhttp.open("get","http://localhost:8080/ServletDemos/timeMsg.do",true);
- //设定http头
- xmlhttp.setRequestHeader("Content-Type","application/x-www-form-unlencoded");
- //发送请求
- xmlhttp.send(null);
- }
- </script>
- </head>
- <body>
- <span id="msg"></span><br>
- <input type = "button" value="单击此按钮" onClick="ok()">
- </body>
- </html>
TimeMsg.java
- package com.wangdq;
- 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;
- /**
- * Servlet implementation class,TimeMsg
- */
- @WebServlet("/timeMsg.do")
- public class TimeMsg extends HttpServlet {
- private static final long serialVersionUID = 1L;
- public TimeMsg() {
- super();
- }
- protected void doGet(HttpServletRequest request,IOException {
- response.setContentType("text/plain;charset=UTF-8");
- PrintWriter out = response.getWriter();
- out.write("现在时间是: "+getCurrentDateAndTime()+" 欢迎您!");
- out.flush();
- out.close();
- }
- /**
- * 获取当前系统时间
- */
- private String getCurrentDateAndTime() {
- String currentDate = "";
- SimpleDateFormat sdf = new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
- currentDate = sdf.format(new Date( ));
- return currentDate;
- }
- protected void doPost(HttpServletRequest request,HttpServletResponse response)
- throws ServletException,IOException {
- this.doGet(request,response);
- }
- }
运行结果如下图所示: