<script language='javascript' src='ajaxbase.js'></script>
<script language='javascript'>
function ajaxTest(obj){
document.getElementById(obj).innerHTML = "正在加载内容...";
currentPos = obj;
send_request("hello.do");
}
</script>
2.执行处理的HelloAction.java如下:
package zhyt;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class HelloAction extends Action {
/* (non-Javadoc)
* @see org.apache.struts.action.Action#execute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
public ActionForward execute(ActionMapping arg0, ActionForm arg1,
HttpServletRequest arg2, HttpServletResponse arg3) throws Exception {
// TODO Auto-generated method stub
return (arg0.findForward("ok"));
}
}
3.在struts-config.xml中增加action描述如下:
<action></action>
path="/hello"
type="zhyt.HelloAction">
<forward name="ok" path="/ok.jsp"></forward>
4.增加视图页面ok.jsp如下:
<%@ page contentType="text/html; charset=gbk" language="java" errorPage="error.jsp" %>
<%
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires", 0);
%>
恭喜,如果你看到这些文字,说明测试成功!
5.当然了,还不能少了ajaxbase.js:
//要注意,每一个独立的函数或这是变量都要顶列头写出,否则将会出错
var http_request = false;
var currentPos = null; //这是全局变量,一定要加上,
//后面的函数调用时才能保证用的是一个
function send_request(url) {//初始化、指定处理函数、发送请求的函数
http_request = false;
//开始初始化XMLHttpRequest对象
if(window.XMLHttpRequest) { //Mozilla 浏览器
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {//设置MiME类别
http_request.overrideMimeType('text/xml');
}
}
else if (window.ActiveXObject) { // IE浏览器
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) { // 异常,创建对象实例失败
window.alert("不能创建XMLHttpRequest对象实例.");
return false;
}
http_request.onreadystatechange = processRequest;
// 确定发送请求的方式和URL以及是否同步执行下段代码
http_request.open("GET", url, true);
http_request.send(null);
}
// 处理返回信息的函数
function processRequest() {
if (http_request.readyState == 4) { // 判断对象状态
if (http_request.status == 200) { // 信息已经成功返回,开始处理信息
document.getElementById(currentPos).innerHTML = http_request.responseText;
} else { //页面不正常
alert("您所请求的页面有异常。");
}
}
}