AJAX请求及json对象封装小demo
js中的ajax请求方法
function query(){
var stuName = $("#stuName").val();
var requestUrl = "/s2sh/student/query.action";
var currentPageIndex = $("span[class='currentPageIndex']").val();
var pageSize =$("input[class='pageSize']").val();
$.ajax( {
url :requestUrl,
type : 'post',
dataType:'json',
data: "stuName="+escape(escape(stuName))+"¤tPageIndex="+currentPageIndex+"&pageSize="+pageSize,
success : function(result){
var stus = result.students;
$("#stuBody").html("");
for(var i=0;i<stus.length;i++){
$("#stuBody").append("<tr><td>"+stus[i].stuName+"</td><td>"+stus[i].stuSex+"</td><td>"+
stus[i].stuBir+"</td><td>"+stus[i].stuAdd+"</td><td><a href='#' onclick='editItem("+stus[i].stuId+");'"+
">修改</a> <a href='#' onclick='deleteItems("+stus[i].stuId+");' >删除</a></td></tr>");
}
$("span[class='totalCount']").html(result.totalCount);
$("span[class='currentPageIndex']").html(result.currentPage).val(result.currentPage);
$("span[class='totalPage']").html(result.totalPage).val(result.totalPage);
},error:function(err){
alert( '系统内部错误'+err);
}
});
}
Action的接受及封装
public class StudentAction {
public StudentService studentService;
private String stuName;
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public StudentService getStudentService() {
return studentService;
}
public void setStudentService(StudentService studentService) {
this.studentService = studentService;
}
public void query() {
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
String tempName = unescape(request.getParameter("stuName"));
try {
students=studentService.queryStuByName(tempName,currentPageIndex,pageSize);
response.setContentType("text/html;charset=UTF-8");
response.getWriter().print(getStudentListJSON(students));
} catch (Exception e) {
e.printStackTrace();
}
}
public String getStudentListJSON(List<Student> students)
{
StringBuffer retVal=new StringBuffer("{'students':[");
int i=0;
for(Student t:students){
if(i!=0)
{
retVal.append(",");
}
retVal.append("{");
retVal.append("\"stuId\":\""+t.getStuId()+"\"");
retVal.append(",\"stuName\":\""+t.getStuName()+"\"");
retVal.append(",\"stuSex\":\""+t.getStuSex()+"\"");
retVal.append(",\"stuBir\":\""+t.getStuBir()+"\"