JSON & Ajax (syntax format + parsing json)

Posted by adyre on Fri, 28 Jan 2022 22:55:52 +0100

1.json rules

Reading guide module: development history:
At the beginning of the 21st century, Douglas Crockford looked for a simple data exchange format,
Can exchange data between servers. At that time, the common data exchange language was XML,
But Douglas Crockford thinks that XML generation and parsing are too troublesome,
So he proposed a simplified format, that is, Jason.

JSON: is a lightweight data exchange format. Based on a subset of ECMAScript (js specification formulated by the European Computer Association), it uses a text format completely independent of the programming language to store and represent data. The concise and clear hierarchy makes JSON an ideal data exchange language. It is easy for people to read and write, but also easy for machine analysis and generation, and effectively improves the network transmission efficiency

In short: is a way / format to store data

Similar technologies are xml

JSON syntax rules:
1. Objects are represented as key value pairs
2. Data is separated by commas
3. Curly braces save objects
4. Save array in square brackets

For example:

{
    "name": "China",
    "province": [{
        "name": "Heilongjiang",
        "cities": {
            "city": ["Harbin", "Daqing"]
        }
    }, {
        "name": "Guangdong",
        "cities": {
            "city": ["Guangzhou", "Shenzhen", "Zhuhai"]
        }
    }, {
        "name": "Taiwan",
        "cities": {
            "city": ["Taipei", "Kaohsiung"]
        }
    }, {
        "name": "Xinjiang",
        "cities": {
            "city": ["Urumqi"]
        }
    }]
}

China: Heilongjiang, Guangdong, Taiwan, Xinjiang, and their major cities
ps: we can also use online tool verification to save time and effort: https://www.sojson.com/

Development: bson
Continue to expand: ProtoBuf

2. Usage of Ajax in jquery

2.0. Local loading of Ajax $("#div1") Load implementation method (if there is no background program, use this)

  1. What is Ajax?

It refers to a web development technology for creating interactive web applications
It is a technology that can update some web pages without reloading the whole web page

In short: it is a technology to obtain data asynchronously without refresh (local refresh)

Parameters:

  • The required URL parameter specifies the URL you want to load: uniform resource locator, which can be simply understood as web address.

  • The optional data parameter specifies the set of query string key / value pairs sent with the request: a parameter passed at the time of the request

  • The optional callback parameter is the name of the function executed after the load() method is completed

  • The callback parameter specifies the callback function to be allowed after the load() method is completed.

  • The callback function can set different parameters:

    • responseTxt - contains the result content when the call is successful
    • statusTXT - contains the status of the call
    • xhr - contains the XMLHttpRequest object
<!DOCTYPE html>
<html>
    <head>
    <meta charset="utf-8">
    <title>AJAX Get external data information</title>
    <script src="../js/jquery.js"></script>
        <script>
        $(function(){
	    $("button").click(function()
			{
								//Request file 		// Result content when the request is successful 	 Status code XMLHttpRequest      
		    	$("#div1").load("123.txt",function(responseTxt,statusTxt,xhr)
		    		{
						if(statusTxt=="success")
						{
						    alert("Requested content:"+responseTxt)
						    alert("error:"+xhr.status+": "+xhr.statusText);
							}	    	    
						if(statusTxt=="error")
						{								//Error message for xhr 
						    alert("Status code:"+xhr.status+": "+xhr.statusText);
						}
		    		});
			})
	})
        </script>
    </head>
<body>

<div id="div1"><h2>use jQuery AJAX Modify text content</h2></div>
<button>Get external content</button>

</body>
</html>

2.1 create through XHR object (obsolete, not recommended)

2.2 Ajax implementation through Jquery

Basic principle: Ajax implementation through jquery

  • Introduce jquery.xml into the page JS file
  • It can be used in the corresponding position

Requirements:

  • Button click to make asynchronous request using ajax
  • The requested data is parsed
  • Render the data as a list and display it on the page

http request:

  • get(): get data
  • post() submit data

Status code:

  • There is a problem with the 4xx request. There is a problem with the parameters provided and the path. If I modify the file to movie_list.json123, then the wrong status code 404 will appear
  • The internal logic of 5xx server needs developers to fix the bug by themselves (for example, when executing queries, you can see it by making errors such as "2 / 0")
  • 3xx request forwarding (after deleting, saving and other operations, you will see through Google browser that the first executed status code is 302, and then 200, which is request forwarding)
  • 200: normal

ps: Summary: don't worry about the correctness of 200. It is recommended to find parameters and paths on the page at the beginning of 4X, java code in the background at the beginning of 5X, and forwarding at the beginning of 3X (mainly logical right and wrong)

Steps:

  1. Because there is no background program, we use one at this time json file to act as the data source (that is, movie_list.json), and introduce the file into the project

  2. In the page through $ getJson to get the data (because I want to get the data from the. json file)
    $. getJson(): load JSON data through HTTP GET request.
    Syntax: jQuery getJSON(url, [data], [callback])
    Parameter: url: send request address.
    data: Key/value parameter to be sent.
    Callback: callback function upon successful loading

  3. Create elements in < body > and display them

     <input type="text" value="" name="" />
     <input type="button" id="get_movies" value="Get movie list"" />
      <div id="container">
      	<!--Used to show pictures-->
      	<div class="item">
      		<img src=""  width="200px" height="200px"/>
      		<p>People travel between heaven and earth, suddenly like travelers</p>
      	</div>
      </div>
    
  4. Set the style of the created element

img{
    width: 200px;
    height: 200px;
    border: 1px solid red;
    float: left;
}
p{
    height: 200px;
    line-height: 200px;
    float: left;
    text-align: center;
    margin: 0px;
    padding: 0px;
}
.item{
    border: 1px solid blue;
    height: 204px;
    padding: 1px;
}
  1. Introduce jquery on the page and start writing ajax
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript" src="../jquery/jquery.js" ></script>
		<style type="text/css">
			   img{
				width: 200px;
				height: 200px;
				border: 1px solid red;
				float: left;
			}
			p{
				height: 200px;
				line-height: 200px;
				float: left;
				text-align: center;
				margin: 0px;
				padding: 0px;
			}
			.item{
				border: 1px solid blue;
				height: 204px;
				padding: 1px;
			}
			
		</style>
		<script type="application/javascript">
			$(document).ready(function(){
				
				$("#get_movies").click(function (){
					alert("start ajax");
					$.getJSON("movie_list.json",function(data)
					{
					 alert(data.movies[0].img);	 
					 alert("data.movies.length:"+data.movies.length);	 
						 for (var i = 0; i < data.movies.length; i++)
						 {
							var	$img=$("<img src='../img/02.jpg' width='200px' height='200px' />")
				            var $p= $("<p></p>")
				            $img.attr("src",data.movies[i].img);//Set src attribute value for img tag
				            $p.text(data.movies[i].tittle)//Set text value for p label
				            var	$item=$("<div class='item'></div>")//Create a div tag
				            $item.append($img).append($p)//Append the newly created img tag and paragraph p tag to the newly created div tag
				            $("#container").append($item) / / append div to div with id value of container
					    }
					})										
				})				
			})		
		</script>
	</head>
	<body>
		   <!--
           	Author: offline
           	Time: 2019-12-09
           	Description: the purpose of writing 69 lines is to demonstrate to students that when it is turned on ajax The text value in line 69 was not lost at the time of the request. Verify again ajax Asynchronous local refresh
           -->
		  <input type="text" value="" name="" />
		<input type="button" id="get_movies" value="Get movie list"" />
	  <div id="container">
	  	<!--Used to show pictures-->
	  	<div class="item">
	  		<img src=""  width="200px" height="200px"/>
	  		<p>People travel between heaven and earth, suddenly like travelers</p>
	  	</div>
	  </div>
	</body>
</html>

2.3.jquery$.post implements ajax requests

/*$.post(url,params,callback); The first method: submit by post, and the Chinese parameters do not need to be transcoded. If you want to get the json string in the callback, you need to convert it (but there is no one in today's example, and the json string will be converted later)
Schematic Code:*/
alert("Start request Ajax");
var gname=$("#gname").val();
alert("Administrator Name:"+gname);
var url="<%=request.getContextPath() %>/manager.do?method=queryAjax";
alert("Requested URl: "+url);

$.post(url,{manager_name:gname},function (data){
    alert("data:"+data);
    tianxie(data);
});	

2.4.jquery$.getJSON load local json

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<script src="<%=request.getContextPath()%>/js/jQuery/jquery-1.4.4.js" type="text/javascript"></script>
<style type="text/css">
			
			  img{
				width: 200px;
				height: 200px;
				border: 1px solid red;
				float: left;
			}
			p{
				height: 200px;
				line-height: 200px;
				float: left;
				text-align: center;
				margin: 0px;
				padding: 0px;
			}
			.item{
				border: 1px solid blue;
				height: 204px;
				padding: 1px;
			}
		</style>	
		<script type="application/javascript">
			$(document).ready(function(){
				$("#get_movies").click(function (){
							//Get local json 			 Return data of callback function
				    $.getJSON("movie_list.json",function(data)
					{
					 alert(data.movies[0].img);	 
					 alert("data.movies.length:"+data.movies.length);	 
						 for (var i = 0; i < data.movies.length; i++)
						 {
							var	$img=$("<img src='' width='200px' height='200px' />")
				            var $p= $("<p></p>")
				            $img.attr("src",data.movies[i].img);//Set src attribute value for img tag
				            $p.text(data.movies[i].tittle)//Set text value for p label
				            var	$item=$("<div class='item'></div>")//Create a div tag
				            $item.append($img).append($p)//Append the newly created img tag and paragraph p tag to the newly created div tag
				            $("#container").append($item) / / append div to div with id value of container
					    }
					})
				})
			})
		</script>
<body>
	 <input type="text" value="" name="" />
		<input type="button" id="get_movies" value="Get movie list"" />
	  <div id="container">
	  	<!--Used to show pictures-->
	  	<div class="item">
	  		<img src=""  width="200px" height="200px"/>
	  		<p>People travel between heaven and earth, suddenly like travelers</p>
	  	</div>
	  </div>
</body>
</html>	

2.5.jquery parses the data from the background servlet

servlet

	/**
	 * @desc 2.Query all
	 * @param request
	 * @param response
	 * @throws SQLException 
	 * @throws ClassNotFoundException 
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void query(HttpServletRequest request, HttpServletResponse response) throws ClassNotFoundException, SQLException, ServletException, IOException {
		   List<Map<String, Object>> list=managerService.queryAll();
		   String jsonStr=jsonOut(list);
		  // request.setAttribute("list", list);
		   //request.getRequestDispatcher("/manage/manager/list.jsp").forward(request, response);
		   
		   System.out.println("jsonStr:"+jsonStr);
		   PrintWriter out = response.getWriter();
		   out.write(jsonStr);
		   out.flush();
		   out.close();
	}
	/**
	 * @desc  Convert data to json format
	 * @param obj
	 * @return
	 * @throws IOException 
	 * @throws JsonMappingException 
	 * @throws JsonGenerationException 
	 */
	private String jsonOut(Object obj) throws JsonGenerationException, JsonMappingException, IOException {
	
		//1. Instantiate the core class in JackSon package
		ObjectMapper om=new ObjectMapper();
		 //writeValue (parameter, obj): directly serialize the incoming object into json and return it to the client
		 //writeValueAsString (obj): serialize the incoming object into json and return it to the caller
	    String json = om.writeValueAsString(obj);
		
		return json;
	}

html

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<script src="<%=request.getContextPath()%>/js/jQuery/jquery-1.4.4.js" type="text/javascript"></script>
<style type="text/css">
			
			  img{
				width: 200px;
				height: 200px;
				border: 1px solid red;
				float: left;
			}
			p{
				height: 200px;
				line-height: 200px;
				float: left;
				text-align: center;
				margin: 0px;
				padding: 0px;
			}
			.item{
				border: 1px solid blue;
				height: 204px;
				padding: 1px;
			}
		</style>	
		<script type="application/javascript">
			$(document).ready(function(){
				$("#get_movies").click(function (){
							//Get local json 			 Return data of callback function
				    $.getJSON("movie_list.json",function(data)
					{
					 alert(data.movies[0].img);	 
					 alert("data.movies.length:"+data.movies.length);	 
						 for (var i = 0; i < data.movies.length; i++)
						 {
							var	$img=$("<img src='' width='200px' height='200px' />")
				            var $p= $("<p></p>")
				            $img.attr("src",data.movies[i].img);//Set src attribute value for img tag
				            $p.text(data.movies[i].tittle)//Set text value for p label
				            var	$item=$("<div class='item'></div>")//Create a div tag
				            $item.append($img).append($p)//Append the newly created img tag and paragraph p tag to the newly created div tag
				            $("#container").append($item) / / append div to div with id value of container
					    }
					})
				})
			})
		</script>
<body>
	 <input type="text" value="" name="" />
		<input type="button" id="get_movies" value="Get movie list"" />
	  <div id="container">
	  	<!--Used to show pictures-->
	  	<div class="item">
	  		<img src=""  width="200px" height="200px"/>
	  		<p>People travel between heaven and earth, suddenly like travelers</p>
	  	</div>
	  </div>
</body>
</html>

3.java data to json format

When converting an object to a json string, you can use two methods in ObjectMapper:
writeValue (parameter, obj): directly serialize the incoming object into json and return it to the client
writeValueAsString (obj): serialize the incoming object into json and return it to the caller

difference:

writeValueAsString(obj)

//1. Instantiate the core class in JackSon package
		ObjectMapper om=new ObjectMapper();

Map<String,Object> map = new HashMap<String,Object>();
ObjectMapper mapper=new ObjectMapper();
String josn = mapper.writeValueAsString(map );
response.getWriter().write(josn);

writeValue (parameter, obj)

//1. Instantiate the core class in JackSon package
		ObjectMapper om=new ObjectMapper();

Map<String,Object> map = new HashMap<String,Object>();
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(response.getOutputStream(),map);

Topics: Java Javascript JQuery