Java中使用json與前臺Ajax數(shù)據(jù)交互的方法
本文主要為大家分享了Ajax獲取顯示Json數(shù)據(jù)的一種方法,供大家參考,具體內(nèi)容如下
1、首先前臺用Ajax,其中注意dataType一定要選擇json方式,Action成功返回給頁面的Json內(nèi)容是這樣的[{"number":"V006","names":"LiLei"}],可見comment['names']對應(yīng)"names":"LiLei",comment['number']對應(yīng)"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();//調(diào)用接口實現(xiàn)類
this.jsonUtil(list);
return null;
}
3、action頁面專門寫一個方法jsonUtil來做為json方法
// 調(diào)用json工具方法,傳入?yún)?shù)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;
}
}
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助。
相關(guān)文章
springboot整合mybatis plus與druid詳情
這篇文章主要介紹了springboot整合mybatis plus與druid詳情,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的下伙伴可以參考一下2022-09-09

