Ajax&Json Notes

Posted by MrJW on Wed, 02 Oct 2019 16:16:19 +0200

Content today

1. AJAX: 
2. JSON

AJAX:

1. Concept: ASynchronous JavaScript And XML	Asynchronous JavaScript and XML
	1. Asynchronization and Synchronization: Based on Communication between Client and Server
		* The client must wait for the response from the server. The client can't do anything else while waiting.
		* The client does not need to wait for a response from the server. In the process of processing requests by the server, the client can perform other operations.

		Ajax It is a technology that can update some pages without reloading the whole page. [1] 
		//By exchanging a small amount of data with the server in the background, Ajax enables asynchronous updates of web pages. This means that some parts of the page can be updated without reloading the entire page.
		//Traditional web pages (without Ajax) have to overload the entire page if they need to update the content.

		//Enhance user experience

2. The way of realization is as follows:
	1. Native JS Realization (Understanding)
				 //1. Creating Core Objects
	            var xmlhttp;
	            if (window.XMLHttpRequest)
	            {// code for IE7+, Firefox, Chrome, Opera, Safari
	                xmlhttp=new XMLHttpRequest();
	            }
	            else
	            {// code for IE6, IE5
	                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	            }
	
	            //2. Connecting
	            /*
	                Parameters:
	                    1. Request mode: GET, POST
	                        * get In this way, the request parameters are spliced behind the URL. send method is an empty parameter
	                        * post Method, request parameters are defined in send method
	                    2. The requested URL:
	                    3. Synchronous or asynchronous requests: true (asynchronous) or false (synchronous)
	
	             */
	            xmlhttp.open("GET","ajaxServlet?username=tom",true);
	
	            //3. Send requests
	            xmlhttp.send();
	
	            //4. Accept and process response results from the server
	            //Access: xmlhttp.responseText
	            //When to get it? Retrieve when the server responds successfully
	
	            //When the ready state of the xmlhttp object changes, the trigger event onreadystatechange.
	            xmlhttp.onreadystatechange=function()
	            {
	                //Determine whether the readyState ready state is 4 and the status response status code is 200.
	                if (xmlhttp.readyState==4 && xmlhttp.status==200)
	                {
	                   //Get the response result of the server
	                    var responseText = xmlhttp.responseText;
	                    alert(responseText);
	                }
	            }
	2. JQeury Realization way
		1. $.ajax()
			* Syntax: $.ajax({Key value pair});
			 //Send asynchronous requests using $. ajax()
	            $.ajax({
	                url:"ajaxServlet1111" , // Request path
	                type:"POST" , //Request mode
	                //Data: "username = Jack & age = 23", // request parameters
	                data:{"username":"jack","age":23},
	                success:function (data) {
	                    alert(data);
	                },//Callback function after successful response
	                error:function () {
	                    alert("Error...")
	                },//Represents a callback function that will be executed if an error occurs in the request response
	
	                dataType:"text"//Set the format of the received response data
	            });
		2. $.get(): Send out get request
			* Syntax: $.get(url, [data], [callback], [type])
				* Parameters:
					* url: Request path
					* data: Request parameters
					* callback: Callback function
					* type: Types of response results

		3. $.post(): Send out post request
			* Syntax: $.post(url, [data], [callback], [type])
				* Parameters:
					* url: Request path
					* data: Request parameters
					* callback: Callback function
					* type: Types of response results

JSON:

1. Concept: JavaScript Object Notation		JavaScript Object Representation
	Person p = new Person();
	p.setName("Zhang San");
	p.setAge(23);
	p.setGender("male");

	var p = {"name":"Zhang San","age":23,"gender":"male"};

	* json Grammar for storing and exchanging text information
	* Data transmission
	* JSON than XML Smaller, faster, and easier to parse.

2. Syntax:
	1. Basic rules
		* Data in name/Value alignment: json Data is made up of key-value pairs
			* Key quotation marks(Single and double lines)Cause, or use no quotation marks.
			* Value type:
				1. Numbers (integers or floating-point numbers)
				2. String (in double quotation marks)
				3. Logical value ( true or false)
				4. Array (in square brackets)	{"persons":[{},{}]}
				5. Object (in curly brackets) {"address":{"province": "Xie"....}}
				6. null
		* Data is separated by commas: multiple key-value pairs are separated by commas
		* Curly brackets to save objects: Use{}Definition json format
		* Square brackets hold arrays:[]
	2. get data:
		1. json object.Key name
		2. json object["Key name"]
		3. Array objects[Indexes]
		4. ergodic
				 //1. Define the basic format
		        var person = {"name": "Zhang San", age: 23, 'gender': true};
		
		        var ps = [{"name": "Zhang San", "age": 23, "gender": true},
		            {"name": "Li Si", "age": 24, "gender": true},
		            {"name": "Wang Wu", "age": 25, "gender": false}];




// Get all the keys and values in the person object
// for in cycle
/* for(var key in person){
// This is not the way to get. Because it corresponds to person. "name"
//alert(key + ":" + person.key);
alert(key+":"+person[key]);
}*/

		       // Get all the values in ps
		        for (var i = 0; i < ps.length; i++) {
		            var p = ps[i];
		            for(var key in p){
		                alert(key+":"+p[key]);
		            }
		        }


3. Conversion between JSON data and Java objects

	* JSON parser:
		* Common parsers: Jsonlib, Gson, fastjson, jackson
	
	1. JSON to Java objects
		1. Import jackson's related jar packages
		2. Create Jackson Core Object Mapper
		3. Call ObjectMapper's related methods for transformation
			1. readValue(json string data, Class)
	2. Java object transformation JSON
		1. Use steps:
			1. Import jackson's related jar packages
			2. Create Jackson Core Object Mapper
			3. Call ObjectMapper's related methods for transformation
				1. Conversion method:
					* writeValue (parameter 1, obj):
	                    Parameter 1:
	                        File: Converts an obj object to a JSON string and saves it to a specified file
	                        Writer: Converts the obj object to a JSON string and fills the JSON data into the character output stream
	                        OutputStream: Converts obj objects to JSON strings and fills JSON data into byte output streams
	                * writeValueAsString(obj): Converts an object to a json string

				2. note:
					1. @JsonIgnore: Exclude attributes.
					2. @JsonFormat: Attributes worth formatting
						* @JsonFormat(pattern = "yyyy-MM-dd")

				3. Complex java object transformation
					1. List: Array
					2. Map: Object formats are consistent

Case study:

* Check whether the user name exists
	1. The data that the server responds to, when used by the client, should be treated as json Data format is used. There are two solutions:
		1. $.get(type):Take the last parameter type Designated as"json"
		2. Setting up on the server side MIME type
			response.setContentType("application/json;charset=utf-8");

Topics: JSON Javascript Java xml