How to implement asynchronous update of web pages with Ajax

php中世界最好的语言
Release: 2018-02-28 09:41:11
Original
2215 people have browsed it

This time I will show you how Ajax implements asynchronous update of web pages. What are the precautions for Ajax to implement asynchronous update of web pages? Here are practical cases, let’s take a look.

1: The concept of ajax

Full name: Asynchronous Javascript And Xml

AJAX is not a new

programming language, but a Create faster, better and more interactive WEB application technology, which was applied around 1998. Through AJAX, your JS can communicate directly with the server through JS's XMLHttpRequest object without reloading the page. This allows the server to request the desired data instead of the entire page. The core of AJAX is the XMLHttpRequest object of JS. The xhr object was first introduced in IE5 and is an object that supports asynchronous requests.

2: Advantages of ajax

Update data without refreshing.

Communicate with the server asynchronously.

Widely supported based on standards.

Separation of front-end and back-end.

Save bandwidth.

3: Writing steps

1. Create an XMLHttpRequest object.

All modern browsers (IE7+, chrome, firefox, opera, safari) have built-in XMLHttpRequest objects. But IE5 and 6 use ActiveX

Object object.

function getAjax() {
var  xmlhttp = null;
if(window.ActiveXObject){
         xmlhttp = new ActiveXObject(’Microsoft.XMLHTTP’);
} else if(window.XMLHttpRequest){
         xmlhttp = new XMLHttpRequest();
}
return  xmlhttp;
}
Copy after login

2. Open the connection with the Server, specify the sending method, URL, permissions, etc.

open method: Create a new HTTP request and specify the method, URL and verification information of this request.

xhr.open(type, url, async, user, password);

type: HTTP request method, GET, POST, etc. Case insensitivity.

url: Request address.

async: Boolean, whether the request is asynchronous. Default is true. If true, the

callback function specified by the onreadystatechange attribute will be called when the state changes. (Optional)

user: If the server requires authentication, specify the user name here. If not specified, a verification window will pop up when the server requires authentication. (Rarely used, only understood)

password: The password part of the verification information. If the user name is empty, this value will be ignored. (Use less, just understand)

Note:

In AJAX, we are actually simulating normal form submission data. A normal form will send the Content-Type field when POSTing data, so we must specify the value of this field as application/x-www-form-urlencoded in AJAX. And the field names and values ​​are encoded and sent. Use setRequestHeader: individually specify a certain HTTP header of the request.

Note: Data should be encoded using the encodeURIComponent() function.

3. Send instructions.

send(): Send a request to the HTTP server and receive a response.

The synchronous or asynchronous mode of this method depends on the async parameter in the open method. If async is true, this method will return immediately. If it is false, this method will wait for the request to complete or timeout before returning. .

xhr.send(body);

body: Data sent through this request. Just set the GET request to null.

4. Wait for and receive the processing results returned by the server.

5. Client receiving.

6. Release the XMLHttpRequest object.

4: Callback function

Specify the

event processing callback function when the readystate attribute changes through the onreadystatechange attribute.

xhr.onreadystatechange = function(){}

readyState property: Returns the current status of the request.

Status:

0: The object has been created and has not been initialized (the open method has not been called).

1: The object has been created and the send method has not been called yet.

2: The send method has been called. But the current status and HTTP status are unknown.

3: Start receiving data. Because the response and HTTP header are incomplete, errors will occur when obtaining some data through responseBody and responseText.

4: Data reception is completed. At this time, the complete response data can be obtained through responseBody and responseText.

status attribute: Returns the status code of the current request.

200 OK: The requested document has been found and returned correctly.

304 Not Modified: Have a local cached copy of the same server-side content.

403 Forbidden: The requester does not have the appropriate permissions for the requested document.

404 Not Found: The requested document was not found.

statusText attribute: Returns the response line information of the current request.

responseXML attribute: format the response information as an XML Document object and return it.

responseText attribute: Return the response information as a string.

5: JS parsing JSON

Introduction to JSON: (mentioned in the js article)

Definition: Javascript Object Notation, a lightweight text-based data Interchange format is easy for humans to read and write, and can also increase network transmission rates.

Two new methods added to ES5:

JSON.parse: Convert JSON string data into JSON objects.

JSON.stringify: Convert JSON objects to JSON strings.

Note: 1. Browser support: IE8+.

 2. The key or string value in the JSON format string must be wrapped in double quotes.

6: Partial data refresh

Manipulate the corresponding DOM node (such as the paging effect of Comments list)

7: Application of event delegation

Event delegation: Use the bubbling mechanism to delegate child element events to the parent element for execution (for example, some news websites remove news that some users do not like)

8: Separation of front and back ends

The backend is only responsible for data output and business logic processing, while the frontend is responsible for interaction logic and interface display. To put it simply: there is no background program code in the front-end static page, and the background outputs data without HTML tags.

The front-end and back-end separation relies on ajax to realize data interaction. (The specific separation of function packaging is given in the demo)

I believe you have mastered the method after reading these cases. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Related reading:

How to solve the problem of abnormal display after layer.photos() asynchronously modifies the image address


The above is the detailed content of How to implement asynchronous update of web pages with Ajax. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template