Ajax是創建快速動態網頁的技術,通過後臺與服務器少量的數據交互,是網頁實現異步更新。也就是在不整個刷新頁面的情況下,可以更新網頁中的局部區域。
在原始web應用的模式中:
瀏覽器 以 http的形式向服務器發送請求,然後服務器處理請求,然後以響應(HTML+CSS)數據返回給客戶端;
AJXA應用中:
瀏覽器 以http發送的請求到達AJAX引擎,由Ajax向服務器進行請求發送數據,處理完成後,把數據繼續返回給Ajax引擎,再以XML或者字符串數據,返回給瀏覽器;
ajax.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'ajax.jsp' starting page</title>
<script type="text/javascript">
//聲明一個空對象接受XMLHttpRequest
var xmlHttpRequest = null;
function ajaxSubmit()
{//IE瀏覽器
if(window.ActiveXObject)
{
xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest)
{//其他瀏覽器
xmlHttpRequest = new XMLHttpRequest();
}
if( null != xmlHttpRequest )
{//發送請求
xmlHttpRequest.open("GET","servlet/AjaxServlet",true);//以GET方式向服務發送異步請求
xmlHttpRequest.onreadystatechange = ajaxCallBack; //準備接受
xmlHttpRequest.send(null); //發送請求
}
}
function ajaxCallBack()
{ //接受響應
if(xmlHttpRequest.readyState == 4)//等於4說明服務器向客戶端已發送了數據
{
if(xmlHttpRequest.status == 200)//說明發送的數據服務器沒有報任何異常
{
var responseText = xmlHttpRequest.responseText; //以Text的形式解析
document.getElementById("div1").innerHTML = responseText; //插入到HTML文檔中
}
}
}
</script>
</head>
<body>
<input type="button" value="get content from serve" οnclick="ajaxSubmit()"/>
<div id="div1"></div>
</body>
</html>
AjaxServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AjaxServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
System.out.println("doGet invoked");
out.println("Hello World AJAX");
out.flush();
out.close();
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>AjaxServlet</servlet-name>
<servlet-class>com.zhaoming.shopping.servlet.AjaxServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AjaxServlet</servlet-name>
<url-pattern>/servlet/AjaxServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>Index.jsp</welcome-file>
<welcome-file>index.html</welcome-file>
</welcome-file-list>