Home> Java> javaTutorial> body text

How to use json to interact with front-end Ajax data in Java

高洛峰
Release: 2017-01-12 09:12:21
Original
1368 people have browsed it

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']); }); } });
Copy after login


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; }
Copy after login


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); }
Copy after login


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; } }
Copy after login


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!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!