This article mainly shares a method for Ajax to obtain and display Json data for your reference. The specific content is as follows
1. First, use Ajax at the front desk. Note that the dataType must be selected as json. The Action returns to the page successfully. The Json content is like this [{"number":"V006","names":"LiLei"}]. It can be seen that comment['names'] corresponds to "names":"LiLei" and comment['number'] corresponds to " 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. The Ajax URL points to the mystudent method in the java action. The returned list is actually an object Student, including the names and number fields
public String mystudent() throws Exception{ List list=priceService.query();//调用接口实现类 this.jsonUtil(list); return null; }
3. The action page specifically writes a method jsonUtil as the json method
// 调用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. I use a comparison method New json package 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; } }
The above is the entire content of this article, I hope it will be helpful to everyone's learning.
For more related articles on how to use json to interact with front-end Ajax data in Java, please pay attention to the PHP Chinese website!