Links to the original text: https://www.cnblogs.com/shuilangyizu/p/9750428.html
Explain
Because in general, the browser (front-end) sends requests and the server (back-end) responds to json data, this paper describes it with js.
1. The server returns json data
Way 1: Return JSON format data (JSON object)
/** * Return to json * @param request * @param response * @param session */ @RequestMapping("/returnjson") public void returnjson(HttpServletRequest request,HttpServletResponse response, HttpSession session) { response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); PrintWriter wirte = null; JSONObject json = new JSONObject(); try { wirte = response.getWriter(); if(1==1){ json.put("Equality is established", "yes"); }else{ json.put("Equation does not hold", "no"); } } catch (Exception e) { e.printStackTrace(); }finally{ wirte.print(json); wirte.flush(); wirte.close(); }response.getWriter().print(jo); }
Mode 2: Return JSON format string (JSON string)
// Set return character set response.setContentType("charset=utf-8"); String result = "{\"name\":\"Marydon\"}"; // Return data response.getWriter().print(result);
2. Client receives and processes json data
For the first return format
Get (), $. Ajax (), $. post (), $. getJSON () these four ways can get the value directly without any extra processing.
$.post(baseUrl + "/test.do",function(result){ alert(result.name);// Marydon });
For the second return format
Get (), $. Ajax (), $. post (); these three ways require data processing to get values;
$.get(baseUrl + "/test.do",function(result){ // json string - > json object result = eval('(' + result + ')'); alert(result.name);// Marydon });
getJSON(); this way the value can be obtained directly without further processing.
$.getJSON(baseUrl + "/test.do",function(result){ alert(result.name);// Marydon });