JSP页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<script type="text/javascript" src="js/jquery-1.4.1.js"></script>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<SCRIPT type="text/javascript">
function clickButton2(){
$.ajax({
url: 'ajaxRequest?'+Math.random(),//此处Math.random()避免浏览器缓存,ajaxRequest是action
type: 'get',
dataType: 'json',
data:{"bj":$("#bj").val(),"xm":$("#xm").val()},//此处向服务器action:ajaxRequest传数据
error: function(){
alert('Error');
},
success: function(data){
for(var dd in data){
alert(data[dd].name);//这里返回的数据可以用jquery生成表格形式
}
}
});
}
</SCRIPT>
</head>
<body>
班级:<br/>
<input id="bj" type="text">
姓名:<br/>
<input id="xm" type="text">
<input type="button" value="ok" onclick="clickButton2();">
</body>
</html>
Book类(省略getter、setter):
public class Book {
private int id;
private String name;
private int categoryId;
...............
//省略getter、setter
}
ACTION 类:
public class HelloWorld extends ActionSupport {
public void execute2() {
HttpServletRequest rq=ServletActionContext.getRequest();
String bj=rq.getParameter("bj");
String xm=rq.getParameter("xm");
HttpServletResponse response =ServletActionContext.getResponse();
response.setCharacterEncoding("UTF-8");
Book bk=new Book();
bk.setId(1);
bk.setCategoryId(1);
bk.setName("good");
Map<String,Object> mp=new HashMap<String, Object>();
mp.put("li1", bk);
Book bk2=new Book();
bk2.setId(2);
bk2.setCategoryId(3);
bk2.setName(bj+"===我放入"+xm);
mp.put("li2", bk2);
JSONObject jsr=JSONObject.fromObject(mp);//返回的是json对象
//JSONArray jsr= JSONArray.fromObject(mp);//如果用数字形式返回要注意客户端首先也要以数组形式调用d[0],后再以属性方式访问
try {
//这里向页面返回数据
PrintWriter out = response.getWriter();
out.println(jsr);
//这里主要为了在服务器端输出测试
System.out.println(jsr);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
struts.xml文件(部分):
<action name="ajaxRequest" method="execute2" class="HelloWorld">
<result name="success">/test.jsp</result>
</action>