web technology -- Introduction to AJAX

Posted by Zetusko on Mon, 03 Jan 2022 23:18:17 +0100

AJAX

Javaweb - emmm... I don't know how many days it is. happy has been nearly four months

Ajax asynchronous refresh technology

First of all, you should understand the asynchronous refresh technology of AJAX. Local refresh is widely used. The native AJAX steps are also fixed. You can create, register, initialize open, and send the request send

The latter framework actually simplifies the current technology, and mybatis encapsulates the repeated part of jdbc; JDK dynamic agent is an advanced application of reflection; spring is used to create objects. Previously, it was directly new dao(); spring MVC is the transformation of servlets, doing the things before servlets

Ajax

Ajax technology can be seen everywhere, such as Baidu search. The prompt below the search box is Ajax technology. Another function is to detect whether the user name is available after entering the user name; In addition, when the mouse is placed on the primary classification, the secondary classification will be displayed; This is also a partial refresh of Ajax; In addition, the headlines will refresh when they roll to the bottom, which is also Ajax

Global refresh and local refresh

Global refresh: the whole browser is covered by new data, and then a large amount of data is transmitted in the network. The browser needs to load and render the page

The whole process is that the browser sends a request to the server, and then loginServlet Forward processing request to jsp,The data is written into the response body, and then the response is sent to the browser

Local refresh: Send a request inside the browser to obtain data and change part of the contents of the page. Other pages do not need to be loaded and rendered, and the amount of data transmission in the network is small; High efficiency and good experience; The core of AJAX is local refresh

The important structure of local refresh is asynchronous objects, which can communicate with the server

Each asynchronous object can send a request to get data instead of the behavior of the browser

ajax introduces asynchronous JavaScript and Xml

The full name of AJAX is asynchronous JavaScript And XML, that is, asynchronous JavaScript And XML; Through Ajax, you can send asynchronous requests to the server in the browser. The biggest advantage is: no refresh to obtain data; That is, it does not need to refresh the whole page, which is a local refresh technology; AJAX is a new way of combining existing language standards. The whole page is not refreshed after sending the request [ lazy loading, saving resources ]

  • JavaScript: it is responsible for creating asynchronous objects, sending requests, and updating dom objects
  • JSON[xml]: the format of data transmitted in the network, which is used for ajax data transmission; But now JSON is used, but the Ajax name remains the same

As a new technology, Ajax plays an important role, that is, asynchronous refresh; The so-called synchronization and asynchrony have references. For example, the asynchrony and synchronization of clock are clear_ Trigger rules of N and clock signals; Synchronization is clear_n and clock are associated by gate circuit and triggered together; Asynchrony means that there is no correlation between the two triggers; In addition, in multithreading, it is similar to asynchrony without locking. There is no relationship between threads and they execute at will; However, after the synchronization lock is added, they will have an association. When the same object is executed, the association will be forcibly generated in order; One execution, the other can only wait

Advantages and disadvantages of AJAX

advantage:

  • You can communicate with the server without refreshing the page [local refresh]
  • Allows the content of some pages to be updated according to the user's events

Disadvantages:

  • No browsing history, can't go back [because the page hasn't been refreshed]
  • There is a cross domain problem [jump between two applications is not allowed]
  • SEO (poor search engine optimization) --- AJAX and JavaScript are dynamically refreshed, so there is no in the whole response body and can't be crawled

I won't repeat the HTTP protocol, just four parts

xml introduction

XML is an extensible markup language; Extensible markup language - designed to transmit and store data. XML is similar to HTML, except that HTML is a predefined tag and can only be used after the browser; There is a specific format; But XML is all custom tags to represent some data

<servlet>
	<servlet-name></servlet-name>
    <servlet-class></servlet-class>
</servlet>
<servlet-mapping>
	<servlet-name></servlet-name>
    <url-pattern></url-pattern>
</servlet-mapping>

However, JSON is still used to convert data between JavaScript and java. It was demonstrated yesterday, because when object type data is transmitted between java and JSON, the ordinary EL method gives the address rather than the specific content. It is necessary to spell the string in JSON format as an object [JSON is lightweight]

Asynchronous request object

In local refresh, you need to create an object to replace the browser's request behavior. This object exists in memory to replace the browser's request and receive the response data. This object is the asynchronous request object

Global update is synchronous and local update is asynchronous [the browser data is not completely updated]; this asynchronous object is used to exchange data with the server in the background. This asynchronous object is XMLHttpRequest

This asynchronous object can update the web page without reloading the page, send a request to the server and receive data after the page has been loaded; All browsers have built-in XMLHttpRequest objects; Asynchronous objects can be created through simple JS code

var  xmlhttp = new XMLHttpRequest();       //core

This asynchronous object is usually stored in the browser's memory

AJAX asynchronous implementation steps readystatechange

1. Create asynchronous objects

Use new XMLHttpRequest() in JavaScript to create asynchronous objects

2. Bind the event onreadstatechange to the asynchronous object

Whenever the readstate changes, this readystatechange event will be triggered. A handler function func1 will be assigned to the event to read the data returned by the server by judging the state of the XMLHttpRequest object. The attribute of the asynchronous object associated with this event is readyState

readyState attribute [state change]

The status of XMLHttpRequest changes from 0 to 4

  • 0: the request is uninitialized, creating an asynchronous request object var xmlHttp = new XMLHttpRequest();
  • 1: Initialize asynchronous object, xmlhttp Open (request mode, request address, true);
  • 2: Asynchronous object sends request xmlhttp send();
  • 3: The asynchronous object receives the response data and returns the data from the server, which is processed internally by XMLHttpRequest
  • 4: The asynchronous request object has parsed the data, and the data can be read at this time

In short, 0 is the new object; 1 is initialization, and the open method specifies the address and mode; 2 is to send a request; 3 is that the server obtains the data - the original data is used internally; 4 indicates that the asynchronous object has been parsed [3 is not generally used, 4 is the most commonly used] 4 status. The developer gets the data and updates the current page - the data is refreshed locally, and the page is updated

Status attribute [network status]

Another important attribute of the asynchronous object is status, which can be used to represent the network status, such as 200404500; 200 indicates success, 404 indicates foreground error, and 500 indicates server code error

Therefore, it takes 200 to indicate that the network request is successful

xmlHttp.onreadstatechange = function(){
	//Treatment scheme
    if(xmlHttp.readyState == 4 && xmlHttp.status == 200){//200 indicates that the request was successful
        //Get the parsed data and update the page
        var data = xmlHttp.responseText;
        document.getElementById("name").value = data; //This successfully updated the data
    }
}

3. Initialize the asynchronous request object open

The asynchronous method is open

xmlHttp. Open (request mode: GET or POST, server access address, asynchronous or synchronous) asynchrony is to select true

//such as
xmlHttp.open("get","loginServlet?name=zhangsan&pwd=1234",true);

4. Send requests using asynchronous objects

You can directly use the method of asynchronous object xmlhttp sendO; This request can be sent to the server

Get the data returned by the server

Get data or use the property responseText of the asynchronous object

xmlhttp.responseText
xmlHttp.onreadstatechange = function(){
	//Treatment scheme
    if(xmlHttp.readyState == 4 && xmlHttp.status == 200){//200 indicates that the request was successful
        //Get the parsed data and update the page
        var data = xmlHttp.responseText;
        document.getElementById("name").value = data; //This successfully updated the data
    }
}

Callback: this function will be called automatically when the request status changes; So programmer is just a writer, not a caller

Examples of ajax usage

ajax uses four steps: creating objects, binding events, initializing and sending requests;

Here is an example to calculate bmi; The browser gives height and weight, gets bmi and gives user feedback; ajax is not used here first; Use global refresh first

Global refresh

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>AJAXdemo</title>
</head>
<body>
	<form action="bmiServlet" method="post">
		full name   : <input type="text" name="user"/><br>
		height m  : <input type="text" name = "height"/><br>
		weight kg : <input type="text" name ="weight"/><br>
		<input type="submit" value="Submit"/>
	</form>
</body>
</html>

Then a simple server-side control layer servlet

package cfeng.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/bmiServlet")
public class bmiServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		//Receive request parameters
		String user = request.getParameter("user");
		String height = request.getParameter("height");
		String weight = request.getParameter("weight");
		
		//The code for calling the business layer was originally encapsulated in the service layer. It is too simple to handle it in the control layer
		//Calculate bmi
		float h = Float.valueOf(height);
		float w = Float.valueOf(weight);
		float bmi = w/(h*h);
		//Judge bmi range
		String msg = "";
		if(bmi <= 18.5) {
			msg = "You're thinner";
		}else if(bmi > 18.5 && bmi <= 23.9) {
			msg = "Yours bmi It's normal";
		}else if(bmi > 24 && bmi <= 27) {
			msg = "You're fat";
		}else {
			msg = "You are very fat";
		}
		msg = "Hello," + user + "sir/ma'am : " +"Yours bmi yes-->" + bmi + " therefore," + msg;
		
		//Put the processing results into the scope and forward them to the view layer for display
		request.setAttribute("msg", msg);
		request.getRequestDispatcher("/result.jsp").forward(request, response);
	}

}

Finally, a simple jsp page of the view layer

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Results page</title>
</head>
<body>
	<p>display bmi result</p>
	<h3> ${msg} </h3>  <!-- Simplified version el expression -->
</body>
</html>

The above is a standard way to write global refresh. Now you can try it. Instead of using jsp, you can directly use response [which also belongs to the view layer]. Here, the address bar displays the address of the servlet, because request forwarding is the first path, although the output stream is only open here; redirection is the last address

Use response to output [response object] - the initial writing method

package cfeng.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/bmiServlet")
public class bmiServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		//Receive request parameters
		String user = request.getParameter("user");
		String height = request.getParameter("height");
		String weight = request.getParameter("weight");
		
		//The code for calling the business layer was originally encapsulated in the service layer. It is too simple to handle it in the control layer
		//Calculate bmi
		float h = Float.valueOf(height);
		float w = Float.valueOf(weight);
		float bmi = w/(h*h);
		//Judge bmi range
		String msg = "";
		if(bmi <= 18.5) {
			msg = "You're thinner";
		}else if(bmi > 18.5 && bmi <= 23.9) {
			msg = "Yours bmi It's normal";
		}else if(bmi > 24 && bmi <= 27) {
			msg = "You're fat";
		}else {
			msg = "You are very fat";
		}
		msg = "Hello," + user + "sir/ma'am : " +"Yours bmi yes-->" + bmi + " therefore," + msg;
		
		//Put the processing results into the scope and forward them to the view layer for display
//		request.setAttribute("msg", msg);
//		request.getRequestDispatcher("/result.jsp").forward(request, response);
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();  //IO stream standard, enable output, refresh, close
		out.println(msg);
		//wipe cache 
		out.flush(); //Show now
		//Close flow
		out.close();
	}
}

This is also the normal output. The returned string is the global refresh, and the whole page will change

Because it is the data sent by the form, the server response will refresh the whole page

Because it is a request sent by a form, there is no asynchronous object, that is, the whole page. Therefore, the data of the response body is returned to the whole page and displayed on the page. However, if it is a request sent by an asynchronous object, the returned data is handed over to the ajax asynchronous object instead of responding to the page

Local refresh

The idea of implementation here is

//readme.txt

1.newly build jsp,use XMLHttpRequest Asynchronous object
  Create object, bind event, initialize open,Send request send
  
2.Create server servlet,Receive and process data, and output the data to asynchronous object

First write an index page

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>AJAXdemo</title>
		<script type="text/javascript">
			doAJAX = function() {
				//Get all the data entered by the user
				var name = document.getElementById("name").value;
				var h = document.getElementById("h").value;
				var w = document.getElementById("w").value;
				
				var xmlhttp = new XMLHttpRequest();
				//Binding event
				xmlhttp.onreadystatechange = function() {
					//Refresh page
					if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
						//alert(xmlhttp.responseText);    Debug found path error
						var data = xmlhttp.responseText;
						alert(data);
						document.getElementById("result").innerText = data;
					}
				}
				
				var uri = "/AjaxTest/bmi?user=" + name +"&weight="+ w + "&height="+h;
				//initialization
				xmlhttp.open("get",uri,true);
				//Send request
				xmlhttp.send();
			}
		</script>
	</head>
	<body>
		full name   : <input id="name" type="text"/><br>
		height m  : <input id="h" type="text" /><br>
		weight kg : <input  id="w" type="text"/><br>
		<input type="button" value="calculation bmi" onclick="doAJAX()"/>
		<br><br><br>
		<span id="result">Waiting to load data</span>
	</body>
</html>

The main difference between this and the above global refresh is that the form is not used, because ajax does not use the form to submit the request; So the button does not need name

<script type="text/javascript">
		var xmlhttp = new XMLHttpRequest();
		//Binding event
		xmlhttp.onreadystatechange = function() {
			//Refresh page
			}
		//initialization
		xmlhttp.open("POST","/bmiServlet",true);
		//Send request
		xmlhttp.send();
</script>

Here is a js script to create an asynchronous object; Each asynchronous object can send a request; When the button is clicked, an event is triggered to create an xmlhttp asynchronous object

Use alert debugging in the bound event and find that the state changes from 1 to 4; The situation is the same as envisaged; xhr is short for asynchronous request; Here, 0 is invisible, and 4 means that the data is returned and parsed successfully

The servlet writes the data to the response body, and the asynchronous object can fetch the data and use it

The local object here is equivalent to the following buttons. Only the asynchronous object in the button will send requests and receive data, and other parts of the page will not change and will not be affected

In this process, there was a small error. The problem was found only by using F12 network debugging. Part of 404 is the path problem. js here is the foreground path, so the project name should be added

Here, we write the data into the div [the old version of Firefox browser does not support innerText, just on the new version of EDGE] ah

The java code is still the same as the previous response output code

In this way, two files, one java and one jsp, realize the asynchronous refresh of native ajax. When we click the button, we get the data, but the page is not refreshed, which is different from the previous refresh

That is, native ajax Is in JavaScript In the script, the background control layer code directly uses the output stream to output the response data to the user ajax Asynchronous object, and then ajax Asynchronous object XMLHttpRequest of responseText Property receives the output data of the record

ajax Native programming is and JDBC The same is fixed. The corresponding event is triggered and created ajax Asynchronous object, registration event, initialization open,Send request send;  The condition in the event is xhr.readyState == 4 && xhr.status == 200

ajax in JSON format

What is returned above is an ordinary text. What should I do if I want to return multiple data? Yesterday, I shared and demonstrated how to pass a string in JSON format to JavaScript. JavaScript variables are directly received through el expressions. For asynchronous objects;

Objects in java and JavaScript are not interlinked; The object in JavaScript is in JSON format, while the object in java transmits an address. This address can only be found by variables in java, but variables in JavaScript cannot be found. Therefore, the data of object type should be passed to JavaScript in JSON format, or JSON should be used to transmit multiple data at one time

The control layer of java transmits strings in JSON format instead of JSON objects. There are two forms of JSON objects in JavaScript

JSON string to JSON object

  • Use EL expression to directly take out the data in the field and output it to the response body in JavaScript
  • Using the eval method, note that if data = "{...}", parentheses must be added for conversion; That is, var obj = eval("(" + data + ")");
//The first method is applicable to general global refresh; Because the direct conversion of EL expression requires the use of fields, you can directly use EL expression in JS to convert non JSON objects assigned to variables - mainly shared fields

//The second method is applicable to AJAX, because the JSON string of the response is obtained directly, so the native eval function is used to execute as js code
var data = "{'name':'zhangsan','stuclass':'HC2001'}";
var stu = eval("(" + data + ")");

Synchronous and asynchronous

The third parameter in the open function is of boolean type. true represents asynchrony and false represents synchronization. The difference between synchronization and asynchrony

  • Asynchronous: after sending a request using an asynchronous object, you can perform other operations without waiting for data processing results; That is, the code relative to the whole interface [the whole interface] is asynchronous. For example, the send function does not wait for the servlet's request response before executing the following code; instead, it executes the following code first; other operations will be performed after the response. Similar to multithreading, you can create multiple asynchronous objects. There is no order between them, and they will be executed only after the response
  • Synchronization: it is consistent with the code execution sequence of the interface. Only one request can be executed at any time, so multiple asynchronous objects can only be executed in sequence, which is similar to adding a synchronization lock on the connection; The following code cannot be executed until send() is executed

Synchronization is very inefficient, as is the thread problem, so we should reduce the use of synchronized

Topics: Java Javascript Front-end Ajax