Home Web Front-end HTML Tutorial How to implement asynchronous update of web pages with Ajax

How to implement asynchronous update of web pages with Ajax

Feb 28, 2018 am 09:41 AM
ajax asynchronous Web page

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to send web pages to desktop as shortcut in Edge browser? How to send web pages to desktop as shortcut in Edge browser? Mar 14, 2024 pm 05:22 PM

How to send web pages to the desktop as a shortcut in Edge browser? Many of our users want to display frequently used web pages on the desktop as shortcuts for the convenience of directly opening access pages, but they don’t know how to do it. In response to this problem, the editor of this issue will share the solution with the majority of users. , let’s take a look at the content shared in today’s software tutorial. The shortcut method of sending web pages to the desktop in Edge browser: 1. Open the software and click the "..." button on the page. 2. Select "Install this site as an application" in "Application" from the drop-down menu option. 3. Finally, click it in the pop-up window

What should I do if the images on the webpage cannot be loaded? 6 solutions What should I do if the images on the webpage cannot be loaded? 6 solutions Mar 15, 2024 am 10:30 AM

Some netizens found that when they opened the browser web page, the pictures on the web page could not be loaded for a long time. What happened? I checked that the network is normal, so where is the problem? The editor below will introduce to you six solutions to the problem that web page images cannot be loaded. Web page images cannot be loaded: 1. Internet speed problem The web page cannot display images. It may be because the computer's Internet speed is relatively slow and there are more softwares opened on the computer. And the images we access are relatively large, which may be due to loading timeout. As a result, the picture cannot be displayed. You can turn off the software that consumes more network speed. You can go to the task manager to check. 2. Too many visitors. If the webpage cannot display pictures, it may be because the webpages we visited were visited at the same time.

Possible reasons why the network connection is normal but the browser cannot access the web page Possible reasons why the network connection is normal but the browser cannot access the web page Feb 19, 2024 pm 03:45 PM

The browser cannot open the web page but the network is normal. There are many possible reasons. When this problem occurs, we need to investigate step by step to determine the specific cause and solve the problem. First, determine whether the webpage cannot be opened is limited to a specific browser or whether all browsers cannot open the webpage. If only one browser cannot open the web page, you can try to use other browsers, such as Google Chrome, Firefox, etc., for testing. If other browsers are able to open the page correctly, the problem is most likely with that specific browser, possibly

What to do if the webpage cannot be opened What to do if the webpage cannot be opened Feb 21, 2024 am 10:24 AM

How to solve the problem of web pages not opening With the rapid development of the Internet, people increasingly rely on the Internet to obtain information, communicate and entertain. However, sometimes we encounter the problem that the web page cannot be opened, which brings us a lot of trouble. This article will introduce you to some common methods to help solve the problem of web pages not opening. First, we need to determine why the web page cannot be opened. Possible reasons include network problems, server problems, browser settings problems, etc. Here are some solutions: Check network connection: First, we need

How to solve the 403 error encountered by jQuery AJAX request How to solve the 403 error encountered by jQuery AJAX request Feb 20, 2024 am 10:07 AM

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

How to open php on the web page How to open php on the web page Mar 22, 2024 pm 03:20 PM

Executing PHP code in a web page requires ensuring that the web server supports PHP and is properly configured. PHP can be opened in three ways: * **Server environment:** Place the PHP file in the server root directory and access it through the browser. * **Integrated Development Environment: **Place PHP files in the specified web root directory and access them through the browser. * **Remote Server:** Access PHP files hosted on a remote server via the URL address provided by the server.

How to solve jQuery AJAX request 403 error How to solve jQuery AJAX request 403 error Feb 19, 2024 pm 05:55 PM

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

See all articles