mvc.js
var objXMLHttp;
// ①创建 XMLHttpRequest
function createXMLHttpRequest() {
//对于Mozila FireFox Opera IE8
if (window.XMLHttpRequest) {
objXMLHttp = new XMLHttpRequest();
} else {
var MSXML = [ 'MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0',
'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP' ];
for ( var n = 0; n < MSXML.length; n++) {
try {
objXMLHttp = new ActiveXObject(MSXML[n]);
break;
} catch (e) {
}
}
}
}
createXMLHttpRequest();
document.getElementById("test").onclick = sendRequest;
function sendRequest() {
var url = "../testAjax.action";
//②打开请求的路径和方式
objXMLHttp.open("POST", url, true);
//③指定响应函数
objXMLHttp.onreadystatechange = process;
//④发送请求
objXMLHttp.send(null);
}
//控制器函数
function process() {
//⑤如果服务响应到来
if (objXMLHttp.readyState == 4
&& (objXMLHttp.status == 200 || objXMLHttp.status == 304)) {
//⑥调用视图函数来加载服务
show(objXMLHttp.responseText);
}
}
function show(content) {
//⑦加载模型返回的数据
document.getElementById("show").innerHTML = content;
}
mvc.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>Event JSP</title>
</head>
<body >
<input id="test" type="button" value="测试">
<div id="show"></div>
<script type="text/javascript" src="js/mvc.js">
</script>
</body>
</html>
3)//相关的 java 代码和 struts略
//①
<action name="testAjax" class="com.dish.struts2.action.JavaScriptAction"
method="test001">
</action>
//②
public class JavaScriptAction extends ActionSupport {
private static final long serialVersionUID = -5876348528420767360L;
public String test001() throws IOException {
HttpServletResponse response = ServletActionContext.getResponse();
PrintWriter out = response.getWriter();
out.println("there are something demo is here.");
return null;
}
}