Home>

json as a lightweight data exchange format,Occupies a very important position in the front-end and back-end data exchange.The syntax of json is very simple,The key-value pair representation is used.This article introduces how jquery passes and parses data in json format in the springmvc framework.Friends interested in spring mvc ajax json related learning together

json as a lightweight data exchange format,Occupies a very important position in the front-end and back-end data exchange.The syntax of json is very simple,The key-value pair representation is used.json can convert a set of data represented in a javascript object into a string,This string can then be easily passed between functions,Or passing strings from a web client to a server-side program in an asynchronous application,You can also pass json-formatted strings from the server-side program to the front end and be interpreted by the front end.This string conforms to json syntax, and json syntax is a subset of javascript syntax.So javascript is easy to explain it,And json can represent more complex structures than "name/value pairs".Let's take an example to see how jquery passes/parses data in json format.

1. First 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 () {
    //Pass the string format json object to the background (a json object)
    $("#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) {
        }
      });
    });
    //Pass the json array to the background
    $("#resolvejsonarray"). click (function () {
      var username=encodeuri ($("#username"). attr ("value"));
      var age=encodeuri ($("#age"). attr ("value"));
      //start of array
      var user1={username:username, age:age};
      var allmenu={
        "menu":[]
        };
      allmenu.menu.push (user1);
      var allmenu1=encodeuri (json.stringify (allmenu));
      $.ajax ({
        //json array
         url:"/springmvc6/user/data/resolvejsonarray",        data:"orderjson =" + allmenu1,        success:function (data) {
        }
      });
    });
    //Receive the background json and parse it in the foreground
    $("#resolvejson"). click (function () {
      $.ajax ({
        //Parse the json data returned from the background
        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 add user</h1>
  Name:<input type="text" name="username">
  Age:<input type="text" name="age"><br>
  <input type="button" value="json object">
  <input type="button" value="json array">
  <input type="button" value="front-end parsing json string">
</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 {
  //Receive a json object in string format from the foreground and parse it in the background
  @requestmapping ("/resolvejsonobject")
  public void resolvejsonobject (httpservletrequest request, httpservletresponse response) throws ioexception {
    //decoding
    string str=urldecoder.decode (request.getparameter ("orderjson"), "utf-8");
    jsonobject jb=new jsonobject ();
    //Convert a json format string into a json object and obtain the "username" attribute value
    string o=(string) jb.fromobject (str) .get ("username");
    system.out.println (o);
  }
   //Pass json array string
  @requestmapping ("/resolvejsonarray")
  public void resolvejsonarray (httpservletrequest request, httpservletresponse response) throws ioexception {
    //Decoding, in order to solve Chinese garbled
    string str=urldecoder.decode (request.getparameter ("orderjson"), "utf-8");
    jsonobject jb=new jsonobject ();
    //Convert json formatted string to json array object
    jsonarray array=(jsonarray) jb.fromobject (str) .get ("menu");
    //Get the first object in the json array
    jsonobject o=(jsonobject) array.get (0);//Get the first array result
    //Remove the "username" attribute value of the first object in the json array
    string name=o.get ("username"). tostring ();//Get attribute value
    system.out.println (name);
  }
  //This function returns data in json format,Parse by jquery in the foreground
  @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 pass it as a string in front and back.When we use json to pass data, the main consideration is its transmission efficiency.When two systems need to exchange data,If passed a serialized object,Efficiency is very low,If you pass an array that stores a large number of objects, the efficiency is even more dare to imagine,At this time, if you pass the object or data into a json string,Efficiency will increase a lot.This article only explains the front-end and back-end data transmission and analysis in a single system.JSON transmission between heterogeneous systems is beyond the scope of this article.

The above is the relevant information about how jquery passes and parses data in json format under the SpringMVC framework.Hope you like it.

  • Previous Detailed import and export of module module in AngularJS
  • Next Detailed explanation of JavaScript based on object-oriented creation of objects (2)