AJAX and JSON in java learning

Let's talk about A jax and JSON today.

In the process of project construction, the technology of ajax is generally used for front and back platform interaction, and the data of front and back interaction is made with json. Let's take a look at what ajax and json are.

Ajax

1. What is ajax?

AJAX is a technology that uses JavaScript to send requests to the server and get the server response. It is characterized by asynchronous request and local refresh.

Tips: I've bolded the word "technology" here, because many beginners think AJAX is a library / framework, similar to JQuery/Vue, so many beginners will ask how to install Ajax. In fact, AJAX is a technology.

2. Problems solved by Ajax

The traditional WEB application model works like this: the user's interface operation triggers HTTP request, the server performs some business logic processing after receiving the request, such as saving data, and then returns an HTML page to the client. But this way does not give users a good application experience. When the server is processing data, the user is in a waiting state. Every step of operation needs to wait. Too much waiting will make the user more and more impatient. AJAX is quite different. Through the Ajax engine, it makes the application process very natural and smooth, because it only exchanges useful data with the server, and unnecessary data such as page display will not be reloaded.

3. The principle of Ajax

The full name of Ajax is Asynchronous JavaScript and XML (Asynchronous JavaScript and XML). Among them, Asynchronous means Asynchronous, which is different from the synchronous way used in traditional web development.

So what is asynchronous and what is synchronous?

In case of synchronization, the client must wait for the response from the server. The client cannot do anything else while waiting. This operation must be completed before the next step is executed. During the waiting period, the browser will suspend execution of any subsequent js code;

Asynchronously, the client does not need to wait for a response from the server. In the process of processing the request by the server, the client can do other operations. But [tell] the browser to do it, and [tell] is an instant thing, and then continue to carry out the next step. When the result returns, the browser will inform js to execute the corresponding callback. As shown below:

[the external link image transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-tmzbfp06-1592204591533) (D: \ amyjavafile \ JavaWeb \ day22_ Ajax & JSON \ notes \ synchronous and asynchronous. bmp)]

4.ajax implementation steps

4.1. Native JS implementation (understanding)
//First, create the XMLHttpRequest object
var xmlHttp = new XMLHttpRequest();

function CommentAll() {
    //Second, register the callback function
    xmlHttp.onreadystatechange = callback1;
  
    //Step 3: configure the request information, open(),get
    //After the parameters under the get request are added to the url,. Ashx? Methodname = getallcomment & STR1 = STR1 & STR2 = STR2
    xmlHttp.open("post", "/ashx/myzhuye/Detail.ashx?methodName=GetAllComment", true);

    //Request header information needs to be configured under post request
    //xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    //Step 4: send the request. Put the parameters to be passed in the post request
    xmlHttp.send("methodName = GetAllComment&str1=str1&str2=str2");//"

}

//Step 5: handle according to different responses
function callback1() {
    if (xmlHttp.readyState == 4)
        if (xmlHttp.status == 200) {
            //Get the returned data
            var data = xmlHttp.responseText;
            //json string to json format
            data = eval(data);
            $.each(data,
                function (i, v) {
                    alert(v);
                });
        }
}

4.2 jqeury implementation mode
        1. $.ajax()
			* Syntax: $.ajax({Key value pair});
			 //Use $. ajax() to send asynchronous requests
	            $.ajax({
	                url:"ajaxServlet1111" , // Request path
	                type:"POST" , //Request method
	                //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 the callback function that will execute if an error occurs in the request response
	
	                dataType:"text"//Format 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: Type of response result

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

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 Syntax 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 Quotes(Single and double)It can be enclosed without quotation marks
			* Value type:
				1. Number (integer or floating point)
				2. String (in double quotes)
				3. Logical value(true or false)
				4. Array (in square brackets)	{"persons":[{},{}]}
				5. Object (in curly braces) {"address":{"province": "Shaanxi"....}}
				6. null
		* Data separated by commas: multiple key value pairs separated by commas
		* Curly braces saving objects: Using{}definition json format
		* Square bracket save array:[]

2. get data:
		1. json object.Key name
		2. json object["Key name"]
		3. Array object[Indexes]
		4. ergodic
				 //1. Define 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 loop
		       /* for(var key in person){
		            //It's not good to get it this way. Because it's equivalent to person."name"
		            //alert(key + ":" + person.key);
		            alert(key+":"+person[key]);
		        }*/
		
		       //2. Get all 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. Convert JSON to Java object
		1. Import the related jar package of jackson
		2. Create the Jackson core object ObjectMapper
		3. Call related methods of ObjectMapper for conversion
			1. readValue(json string data, Class)
	2. Java object conversion JSON
		1. Operation steps:
			1. Import the related jar package of jackson
			2. Create the Jackson core object ObjectMapper
			3. Call related methods of ObjectMapper for conversion
				1. Conversion method:
					*Writevalue (parameter 1, obj):
	                    Parameter 1:
	                        File: converts the obj object to a JSON string and saves it to the specified file
	                        Writer: convert obj object to JSON string and fill JSON data into character output stream
	                        OutputStream: convert obj object to JSON string and fill JSON data into byte output stream
	                *writeValueAsString(obj): converts an object to a json string

				2. Notes:
					1. @JsonIgnore: exclude attribute.
					2. @JsonFormat: the attribute is worth formatting
						* @JsonFormat(pattern = "yyyy-MM-dd")

				3. Complex java object transformation
					1. List: array
					2. Map: consistent object format

Tags: JSON Javascript Java xml

Posted on Mon, 15 Jun 2020 05:12:34 -0400 by reliable