为了提高页面的友好度,开始学习ajax。关于这方面的资料很多,但是还是准备将自己的代码写下来,将来找起来也方便些。
首先是Action端的代码
public class AjaxAction extends ActionSupport {//ActionSupport似乎十分重要,如果没有就会出错
public String info() {
try {
HttpServletResponse response = ServletActionContext.getResponse();
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.print("Hello World");
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;//由于不用跳转页面,所以也就不需要返回字段
}
}
Struts.xml的代码
<!-- Ajax -->
<action name="ajaxAction_*" class="action.AjaxAction"
method="{1}">
<result />
</action>
js端的代码
var xmlHttp;
function createXmlHttpRequest(){
if(window.ActiveXObject){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}else if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}
}
function showSecret(){
createXmlHttpRequest();
xmlHttp.onreadystatechange = callback;
var url = "http://localhost:8080/xxxx/ajaxAction_info";
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function callback(){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
alert("the server replied with "+xmlHttp.responseText);
}else{
alert("the server cannot reply");
}
}
}
最后是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>main page</title>
<script language="javascript" src="<%=request.getContextPath() %>/js/ajax.js"></script>
</head>
<body>
<form action="" method="post">
<input type="button" value="点我" onclick="javascript:showSecret()">
</form>
</body>
</html>