一个使用Ajax小示例:
//jsp页面
<%@ page language="java" pageEncoding="GBK"%>
<html>
<head>
<title>Ajax Hello sunyang</title>
<script language="JavaScript" type="text/javascript">
//创建XMLHttpRequest的函数
function createXMLHttp(){
var request;
//得到当前浏览器
var browser=navigator.appName;
//如果是IE浏览器
if(browser=="Microsoft Internet Explorer"){
request=new ActiveXObject("Microsoft.XMLHttp");
return request;
}
//非IE浏览器
else{
request=new XMLHttpRequest();
return request;
}
}
//定义XMLHttpRequest变量
var xhr=createXMLHttp();
function HelloSunyang(){
//跳转路径
var url="sayHello.do?name=" + document.forms[0].name.value;
//跳转
xhr.open("GET",url,true);
//设置回调函数为getHello
xhr.onreadystatechange=getHello;
//将请求发送
xhr.send();
}
function getHello(){
//判断XmlHttpRequest状态
if(xhr.readyState==4){
//设置变量helloStr的值为响应返回值
var helloStr = xhr.responseText;
//将响应返回值显示在名为hello的div标签中
document.getElementById("hello").innerHTML=helloStr;
}
}
</script>
</head>
<body>
<table>
<tr>
<td>hello sunyang</td>
</tr>
<tr>
<td>
<form>
your name: <input type="text" name="name" value=""/>
</form>
</td>
</tr>
<tr>
<td>
<!--定义按钮,并设置点击此按钮调用HelloSunyang函数-->
<input type="button" name="" value="hello" οnclick="HelloSunyang()">
</td>
</tr>
<tr>
<td>
<!--接收返回内容的div标签-->
<div id="hello"></div>
</td>
</tr>
</table>
</body>
</html>
//web.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>helloajax</servlet-name>
<servlet-class>sunyang.Hello</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>helloajax</servlet-name>
<url-pattern>/sayHello.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>sayHello.jsp</welcome-file>
</welcome-file-list>
</web-app>
//一个java类
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
public class Hello extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String name=req.getParameter("name");
String result="Hello "+name;
req.setAttribute("name", result);
RequestDispatcher rd=req.getRequestDispatcher("hello.jsp");
rd.forward(req, resp);
}
}
//重定向到hello.jsp页面
<%@ page language="java" pageEncoding="gbk"%>
<html>
<body>
<%=request.getAttribute("name") %>
</body>
</html>