Java中應用json與前台Ajax數據交互的辦法。本站提示廣大學習愛好者:(Java中應用json與前台Ajax數據交互的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是Java中應用json與前台Ajax數據交互的辦法正文
本文重要為年夜家分享了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; }
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; } }
以上就是本文的全體內容,願望對年夜家的進修有所贊助。