This article mainly shares a method for Ajax to obtain Json data for your reference. The specific content is as follows
1. First, use Ajax in the front desk, and note that dataType must choose the json method. The Json content returned to the page successfully is as follows [{"number":"V006","names":"LiLei"}]. It can be seen that comment['names'] corresponds to "names":"LiLei", 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("name"+ comment['names']); alert("student number"+comment['number']); }); } }); 2. Ajax's URL points to the mystudent method in java action. The returned list is actually an object Student, including names and nunmber fields
public String mystudent() throws Exception{ List list=priceService.query();//Calling the interface implementation class this.jsonUtil(list); return null; } 3. The action page specifically writes a method jsonUtil as a json method
// Call the json tool method and pass in the parameter alist public void jsonUtil(Object accountlist) throws Exception { HttpServletResponse response = ServletActionContext.getResponse(); log.info("JSON format: " + accountlist.toString()); String returnJson = JsonConvert.returnJson(accountlist); response.setCharacterEncoding("utf-8"); response.getWriter().println(returnJson); } 4. I'm using a relatively 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 all about this article, I hope it will be helpful to everyone's learning.