本文主要為大家分享了Ajax獲取顯示Json資料的一種方法,供大家參考,具體內容如下
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; }
// 调用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); }
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; } }