Java中使用json與前台Ajax資料互動的方法_java

來源:互聯網
上載者:User

本文主要為大家分享了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; }}

以上就是本文的全部內容,希望對大家的學習有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.