Home > Article > Web Front-end > How to implement JQuery to pass and parse data in Json format under the SpringMVC framework_jquery
As a lightweight data exchange format, json occupies a very important position in front-end and back-end data exchange. The syntax of Json is very simple, using key-value pair representation. JSON can convert a set of data represented in a JavaScript object into a string, which can then be easily passed between functions, or from a web client to a server-side program in an asynchronous application, or A string in json format can be passed from the server-side program to the front-end and interpreted by the front-end. This string conforms to json syntax, and json syntax is a subset of javascript syntax, so javascript can easily interpret it, and JSON can represent more complex structures than "name/value pairs". Let's take a look at how JQuery transfers/parses data in json format through an example.
1. First let’s look at the front-end jsp code:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <script type="text/javascript" src="/springMVC6/js/jquery-1.7.2.js"></script> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript"> $(document).ready(function(){ //传递字符串格式json对象到后台(一个json对象) $("#resolveJsonObject").click(function(){ var userName =encodeURI($("#userName").attr("value")); var age = encodeURI($("#age").attr("value")); var user = {userName:userName,age:age}; var aMenu = encodeURI(JSON.stringify(user)); $.ajax({ url:"/springMVC6/user/data/resolveJsonObject" , data:"orderJson=" + aMenu, success:function(data){ } }); }); //传递json数组到后台 $("#resolveJsonArray").click(function(){ var userName =encodeURI($("#userName").attr("value")); var age = encodeURI($("#age").attr("value")); //数组开始 var user1 = {userName:userName,age:age}; var allMenu={ "menu":[ ] }; allMenu.menu.push(user1); var allMenu1 = encodeURI(JSON.stringify(allMenu)); $.ajax({ //json数组 url:"/springMVC6/user/data/resolveJsonArray" , data:"orderJson=" + allMenu1, success:function(data){ } }); }); //接收后台的json在前台解析 $("#resolveJson").click(function(){ $.ajax({ //解析从后台返回的json数据 url:"/springMVC6/user/data/resolveJson" , type:"post", success:function(data){ var arr=eval(data); alert(arr.length); for(var m = 0;m<arr.length;m++){ alert(arr[m].user.userName); } } }); }); }); </script> </head> <body> <h1>json添加用户</h1> 姓名:<input id="userName" type="text" name="userName"> 年龄:<input id="age" type="text" name="age"><br> <input type="button" id="resolveJsonObject" value="json对象"> <input type="button" id="resolveJsonArray" value="json数组"> <input type="button" id="resolveJson" value="前端解析json字符串"> </body> </html>
2. Use javabean to parse front-end data:
package com.tgb.web.controller.annotation; import java.io.IOException; import java.net.URLDecoder; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.tgb.web.controller.entity.User; @Controller @RequestMapping("/user/data") public class DataController { //接收前台传过来的字符串格式的json对象,在后台进行解析 @RequestMapping("/resolveJsonObject" ) public void resolveJsonObject(HttpServletRequest request,HttpServletResponse response) throws IOException { //解码 String str = URLDecoder.decode(request.getParameter("orderJson"),"UTF-8"); JSONObject jb=new JSONObject(); //将json格式的字符串转换为json对象,并取得该对象的“userName”属性值 String o=(String)jb.fromObject(str).get("userName"); System.out.println(o); } //传递json数组字符串 @RequestMapping("/resolveJsonArray" ) public void resolveJsonArray(HttpServletRequest request,HttpServletResponse response) throws IOException { //解码,为了解决中文乱码 String str = URLDecoder.decode(request.getParameter("orderJson"),"UTF-8"); JSONObject jb=new JSONObject(); //将json格式的字符串转换为json数组对象 JSONArray array=(JSONArray)jb.fromObject(str).get("menu"); //取得json数组中的第一个对象 JSONObject o = (JSONObject) array.get(0);//获得第一个array结果 //取出json数组中第一个对象的“userName”属性值 String name=o.get("userName").toString();//获得属性值 System.out.println(name); } //通过该函数返回json格式的数据,在前台通过JQuery进行解析 @RequestMapping("/resolveJson" ) public void resolveJson(HttpServletRequest request,HttpServletResponse response) throws IOException { List m = (List) new ArrayList(); JSONArray jsons = new JSONArray(); for(int i=0;i<10;i++){ User user = new User(); user.setUserName("name_" + i); m.add(user); } for(int j=0;j<m.size();j++){ JSONObject jsonObject = new JSONObject(); jsonObject.put("user", m.get(j)); jsons.add(jsonObject); } response.getWriter().print(jsons.toString()) ; } @RequestMapping("/toJson" ) public String toJson() { return "/json"; } }
The role of json is not just to be passed as a string in the front and backend. When we use json to transfer data, the more important thing to consider is its transmission efficiency. When two systems need to exchange data, if serialized objects are passed, the efficiency is very low. If an array storing a large number of objects is passed, the efficiency is even more unimaginable. At this time, if Convert objects or data into json strings for transmission, and the efficiency will be greatly improved. This article only explains the front-end and back-end data transmission and analysis in a single system. JSON transmission between heterogeneous systems is not within the scope of this article.
The above is the relevant information on how JQuery transmits and parses data in Json format under the SpringMVC framework. I hope you like it.