1 不带json参数的ajax请求
1)在js里发送请求
$.ajax({
url : 'student/student!listStu.action',
type : 'post',
data : null,
dataType : 'json',
success : function(data) {
//var obj =eval("("+data+")"); // 它的功能是把对应的字符串解析成JS代码并运行
alert(data.length);
var x="";
for(i =0;i<data.length;i++){
x += data[i]["name"]+"#";
}
alert(x);
//console.debug(obj);
}
});
2)action的处理方式
用request获取请求参数
System.out.println("json param:"+student.getName()+arry[0]);
HttpServletResponse response = ServletActionContext.getResponse();
HttpServletRequest request = ServletActionContext.getRequest();
Student st = (Student)request.getAttribute("student");//获取对象
String t[] = request.getParameterValues("arry");//获取数组
System.out.println("%%%"+request.getParameter("age")+"%%%%"+st.getName()+"%%%%%"+t[1]);
HttpServletResponse response = ServletActionContext.getResponse();
//设置headers参数
String fullContentType = "text/plain" + ";charset=" + "utf-8";
response.setContentType(fullContentType);
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
//listStudent = userService.getListStudent();
Student st0 = new Student();
st0.setName("ceny");
st0.setPassword("1234");
listStudent.add(st0);
Student st1 = new Student();
st1.setName("ceny1");
st1.setPassword("12342");
listStudent.add(st1); System.out.println(JSONArray.fromObject(listStudent).toString());
response.getWriter().write(JSONArray.fromObject(listStudent).toString());
response.getWriter().flush();打印的数据类型:[{"id":0,"name":"ceny","password":"1234","teacher":null},{"id":0,"name":"ceny1","password":"12341","teacher":null}]
2 带json参数的ajax请求
1)js传递参数
$.ajax({
url : 'student/student!listStu.action',
type : 'post',
data : "student.name='xiaochen'&student.password='0000'",
dataType : 'json',
success : function(data) {
//var obj =eval("("+data+")"); // 它的功能是把对应的字符串解析成JS代码并运行
alert(data.length);
var x="";
for(i =0;i<data.length;i++){
x += data[i]["name"]+"#";
}
alert(x);
//console.debug(obj);
}
});$.ajax({
url : 'student/student!listStu.action',
type : 'get',
data :{"student.name":20,"arry":[1,2,3]} , /这种参数形式将会转化成上一种参数的传递方式xx=yy&x=yy。。后边传递的是一个数组,需要在后台定义。
dataType : 'json',
success : function(data) {
alert(data.length);
var x="";
for(i =0;i<data.length;i++){
x += data[i]["name"]+"#";
}
alert(x);
}
});2)后台获取json的数据
public String listStu() throws IOException {
System.out.println("json param:"+student.getName()+student.getName()+arry[0]);}
3 post请求
$.post("student/student!listStu.action", {"student.name":20,"arry":[1,2,3]},
function(data) {
var x=eval("("+data+")");//返回的是json格式的字符串,通过eval变成json对象
alert(x);
//alert(x[0]["name"]);
var html = "";
for(var i=0;i<2;i++){
html+=x[i]["name"]+"#";
}
alert(html);
},
"josn"
);传递参数和返回参数均能正常使用。