The downside of traditional development is that all pages in the browser are globally refreshed. If we want to retrieve or update only part of the information on the page, we must apply the technique of partial refresh.

Partial refreshes are also an important way to effectively improve the user experience.

Ajax technology is based on the EXTENSION of JS language, can send requests to the background, and get relevant data from the background, and then the data in the page to do local refresh important technology.

This tutorial will provide a comprehensive overview of Ajax through traditional ajax uses, json manipulation, and advanced techniques such as cross-domain.

Watch online: www.bilibili.com/video/BV15k.

Data download: www.bjpowernode.com/javavideo/1…

What is Ajax?

AJAX = Asynchronous JavaScript and XML.

AJAX is a new way to update parts of a page without having to reload the entire page

AJAX is not a new programming language, but rather a new way to mix and match existing technologies. Techniques used in Ajax include JavaScript, HTML, DOM, XML, CSS, etc. Mostly JavaScript, XML.

XML: The format for sending and receiving data, now using JSON

AJAX requires not only front-end technology, but also back-end (server) cooperation. The server needs to provide data, which is the result of an AJAX request.

Global refresh and local refresh

In a B/S structure project, the Browser (Browse) is responsible for sending the user’s request and parameters to the Server over the network. The Server uses servlets (one of many server-side technologies) to receive the request and return the processing results to the browser.

Browsers render data in HTML, JSP, and use a mix of CSS and JS to help beautify pages or respond to events.

Global refresh

Login request processing:

Index.jsp initiates a login request ——–LoginServlet result.jsp

Initiate request request phase:

The browser now has the contents and data of the Index page in memory:

Server side reply result stage:

Sevlet returns and overwrites the original index page. Result.jsp overwrites the entire browser memory. The entire browser data is refreshed. Redisplay data, styles, labels, etc in the browser window

Global refresh principle:

  1. The browser must personally send the request protocol packet to the server.

  2. This behavior causes the server to send the response packet directly into the browser memory

  3. This behavior causes the browser’s memory to be overwritten

  4. This behavior causes the browser to display only the response data when displaying the data

Local refresh

When the browser displays data, you can see both the response data and the original data in the browser memory in the window

Partial refresh principle:

  1. The browser cannot send requests to the server

  2. The browser delegates the request to a script object in the browser’s memory.

  3. This behavior causes the server to send the response packet directly into the memory of the script object

  4. This behavior causes the script object content to be overwritten, but most of the browser’s memory remains untouched

  5. This behavior causes the browser to display both the original data and the response data when displaying the data

AJAX is a technique for implementing partial refreshes.

Asynchronous request object:

To partially refresh, you need to create an object that is stored in memory instead of the browser making the request.

Initiate the request and receive the response data instead of the browser. This object is called an asynchronous request object.

The global refresh is synchronous, the local refresh is asynchronous. This asynchronous object is used to exchange data with the server in the background. XMLHttpRequest is what we call an asynchronous object.

The XMLHttpRequest object can:

Update a web page without reloading the page

Request data from the server after the page has been loaded

Receives data from the server after the page has been loaded

All modern browsers (IE7+, Firefox, Chrome, Safari, and Opera) have the XMLHttpRequest object built in. With a simple line of JavaScript code, you can create an XMLHttpRequest object

Syntax for creating an XMLHttpRequest object (XHR) : var XMLHTTP =new XMLHttpRequest();

The core object in AJAX is XMLHttpRequest

AJAX asynchronous implementation steps

Introduction to the XMLHttpRequest object

(1) Object creation method

var xmlHttp = new XMLHttpRequest();

(2) onReadStatechange event

When the request is sent to the server, we need to perform some response-based tasks. The onReadyStatechange event is emitted whenever readyState changes. This event can specify a handler function.

Obtain the data returned by the server by determining the status of the XMLHttpReqeust object.

Grammar:

XmlHttp. Onreadystatechange = function () {if (xmlHttp. ReadyState = = 4 && xmlHttp. Status = = 200) {return data processing server}}Copy the code

Processing server returns data

}}Copy the code

Here are three important attributes of the XMLHttpRequest object:

Attribute Description:

Onreadystatechange property: A JS function name or directly defined function that is called whenever the readyState property changes

ReadyState attribute:

The state of XMLHttpRequest exists. It goes from 0 to 4.

• 0: request uninitialized, create asynchronous request object var xmlHttp = new XMLHttpRequest()

• 1: Initializes the asynchronous request object, xmlhttp. open(request method, request address, true)

• 2: Asynchronous objects send requests, xmlhttp.send ()

• 3: The asynchronous object receives response data and returns data from the server. XMLHttpRequest internal processing.

• 4: The asynchronous request object has parsed the data. Only then can the data be read.

The status attribute:

200: "OK"

404: Page not found

(1) Initialize request parameters:

Methods:

Open (Method, URL,async) : Initializes the asynchronous request object

Parameter Description:

  • Method: Request type. GET or POST
  • Url: the servlet address of the server
  • Async: true (asynchronous) or false (synchronous)

Such as:

XmlHttp. Open (" get ", "HTTP: 192.168.1.20:8080 / myweb/query", true)

(2) Send the request

xmlHttp.send()

(3) Receive the data responded by the server

To get a response from the server, use the responseText or responseXML ownership of the XMLHttpRequest object.

ResponseText: get the response data in string form

AJAX example

Global refresh calculates BMI

Requirement: Calculate a user’s BMI. The user enters his height and weight in JSP; The servlet calculates BMI and displays the calculation results and recommendations for BMI.

BMI (BodyMassIndex) is calculated by dividing one’s weight in kilograms by the square of one’s height in meters. It is an international standard used to measure one’s weight, thinness and health

BMI values for adults:

1) Too light: below 18.5

2) Normal: 18.5-23.9

3) Overweight: 24-27

4) Obesity: 28-32

5) Very obese, higher than 32

Development steps:

1. Create a new project in idea named CH01-BMI-Ajax

2. Configure the Tomcat server. If the Tomcat server has been configured, skip this step.

Select the Local

Configure the location of the Tomcat server

Module adds Tomcat support

A window

Option 2 Library

Confirm tomcat

3. Create JSP, define form, have parameters name, weight, height

4. Create a Servlet named BMIServlet

5. The registration servlet

6. Create the result. The JSP

Create the result.jsp file in the web directory

7. Configure the running program and enter parameters. According to bmi

_ueditor_page_break_tag_

Output the response using HttpServletResponse

  1. Create a new JSP: IndexPrint.jsp

  1. Create a new Servlet named BMIServeltPrint

Calculate bmi using ajax requests

  1. New ajax. JSP

  1. Specify the doAjax() function in the head section of ajax.jsp

  1. Copy the BMIServletPrint and rename the BMIServletAjax code unchanged

  2. The registration Servlet

  1. Access Ajax.jsp in your browser

Set a breakpoint on the first line of the BMIServltAjax, then click the button in the JSP to initiate the request and watch what changes when it pops up in the browser

  1. Modify the doAjax() function in ajax.jsp

7. Access ajax.jsp request

Click a button in a JSP, initiate a request, and watch what pops up in the browser

8. Obtain the DOM object value

9. Test sending Ajax requests in the browser

10. Modify the doAjax function