ajax json alert 是object,怎么查看data里面的数据是不是 要的
2015-02-09
展开全部
1、首先前台用Ajax,其中注意dataType一定要选择json方式,Action成功返回给页面的Json内容是这样的[{"number":"V006","names":"LiLei"}],可见comment['names']对应"names":"LiLei",comment['number']对应"number":"V006"。
$.ajax({
type: "post",
url:'apply/mystudent.action?',
cache: false,
dataType : "json",
success: function(data){
$.each(data, function(commentIndex, comment){
alert("姓名"+ comment['names']);
alert("学号"+comment['number']);
});
}
});
2、Ajax的URL指向在java的action中mystudent方法,返回的list其实是一个对象Student,包括了names和nunmber字段
public String mystudent() throws Exception{
List list=priceService.query();//调用接口实现类
this.jsonUtil(list);
return null;
}
3、action页面专门写一个方法jsonUtil来做为json方法
// 调用json工具方法,传入参数alist
public void jsonUtil(Object accountlist) throws Exception {
HttpServletResponse response = ServletActionContext.getResponse();
log.info("JSON格式:" + accountlist.toString());
String returnJson = JsonConvert.returnJson(accountlist);
response.setCharacterEncoding("utf-8");
response.getWriter().println(returnJson);
}
4、我用的是一种比较新的json包jackson
import java.io.StringWriter;
import org.codehaus.jackson.map.ObjectMapper;
public class JsonConvert {
static String jsonStr;
public static String returnJson(Object object) throws Exception{
ObjectMapper objectMapper = new ObjectMapper();
StringWriter stringWriter = new StringWriter();
objectMapper.writeValue(stringWriter, object);
jsonStr = stringWriter.toString();
return jsonStr;
}
}
$.ajax({
type: "post",
url:'apply/mystudent.action?',
cache: false,
dataType : "json",
success: function(data){
$.each(data, function(commentIndex, comment){
alert("姓名"+ comment['names']);
alert("学号"+comment['number']);
});
}
});
2、Ajax的URL指向在java的action中mystudent方法,返回的list其实是一个对象Student,包括了names和nunmber字段
public String mystudent() throws Exception{
List list=priceService.query();//调用接口实现类
this.jsonUtil(list);
return null;
}
3、action页面专门写一个方法jsonUtil来做为json方法
// 调用json工具方法,传入参数alist
public void jsonUtil(Object accountlist) throws Exception {
HttpServletResponse response = ServletActionContext.getResponse();
log.info("JSON格式:" + accountlist.toString());
String returnJson = JsonConvert.returnJson(accountlist);
response.setCharacterEncoding("utf-8");
response.getWriter().println(returnJson);
}
4、我用的是一种比较新的json包jackson
import java.io.StringWriter;
import org.codehaus.jackson.map.ObjectMapper;
public class JsonConvert {
static String jsonStr;
public static String returnJson(Object object) throws Exception{
ObjectMapper objectMapper = new ObjectMapper();
StringWriter stringWriter = new StringWriter();
objectMapper.writeValue(stringWriter, object);
jsonStr = stringWriter.toString();
return jsonStr;
}
}
展开全部
在ajax success中用eval转换返回的对象然后alert
或者打开firebug看控制台ajax请求返回的HTML是什么
或者打开firebug看控制台ajax请求返回的HTML是什么
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
alert 是object 说明返回没成功。要检查下程序哪里有错误
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询