struts2+ajax的簡單實例

爲了提升頁面的友好度,開始學習ajax。關於這方面的資料不少,可是仍是準備將本身的代碼寫下來,未來找起來也方便些。javascript

首先是Action端的代碼html

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端的代碼java

<%@ 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>
相關文章
相關標籤/搜索