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" onclick="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>
原文链接:https://www.f2er.com/ajax/165813.html