Javaweb two ways to return JSON data creationtime--2018 July 25 17:20 author:marydon1. Description
Due to the general situation, the browser (front-end) to send the request, the server (background) response to JSON data, so here with JS to explain;
A server sends the request to the B server, and receives its return JSON data, see at the end of the article recommendation, here no longer repeat!
2. The server returns JSON data
Way one: Return JSON-formatted data (JSON object)
Sets the return JSON data and specifies the character set Response.setcontenttype ("APPLICATION/JSON;CHARSET=UTF-8;"); /Set return data jsonobject Jo = new Jsonobject () jo.put ("name", "Marydon");//Return Data Response.getwriter (). Print (Jo);
Mode two: Return JSON format string (JSON string)
Sets the return character set Response.setcontenttype ("Charset=utf-8"); String result = "{\" name\ ": \" marydon\ "}";//Returns Data Response.getwriter (). Print (result);
3. The client receives and processes the JSON data
For the first return format
$.get (); $.ajax (); $.post (); $.getjson () These 4 ways do not need to do extra processing, directly can take value.
$.post (BaseUrl + "/test.do", function (Result) { alert (result.name);//Marydon});
For the second return format
$.get (); $.ajax (); $.post (); These three methods need to deal with the data in order to get the value;
$.get (BaseUrl + "/test.do", function (Result) { //JSON string-->json object result = eval (' (' + result + ') '); alert (result.name);//Marydon});
$.getjson (); This method directly can be value, no further processing.
$.getjson (BaseUrl + "/test.do", function (Result) { alert (result.name);//Marydon});
Related recommendations:
- How the Struts2 interface receives JSON data submitted by the client
- Javaweb 2 ways to send a POST request (form, JSON)
Javaweb two ways to return JSON data