Ajax: a method for obtaining and displaying Json data

Source: Internet
Author: User

This article mainly uses json to interact with Ajax data at the front end in java.

1. First, the front-end uses Ajax. Note that dataType must select the json mode. The Json content returned by Action to the page is [{"number": "V006 ", "names": "LiLei"}], you can see 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 ID" + 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 nunmber fields.

Public String mystudent () throws Exception {List list = priceService. query (); // call the interface implementation class this. jsonUtil (list); return null ;}


3. On the action page, write a method jsonUtil as the json method.

// Call the json method and input the parameter alistpublic 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 am using a newer 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;}}




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.