search
HomeWeb Front-endHTML TutorialHow to implement asynchronous update of web pages with Ajax

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;
}

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
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
The Future of HTML, CSS, and JavaScript: Web Development TrendsThe Future of HTML, CSS, and JavaScript: Web Development TrendsApr 19, 2025 am 12:02 AM

The future trends of HTML are semantics and web components, the future trends of CSS are CSS-in-JS and CSSHoudini, and the future trends of JavaScript are WebAssembly and Serverless. 1. HTML semantics improve accessibility and SEO effects, and Web components improve development efficiency, but attention should be paid to browser compatibility. 2. CSS-in-JS enhances style management flexibility but may increase file size. CSSHoudini allows direct operation of CSS rendering. 3.WebAssembly optimizes browser application performance but has a steep learning curve, and Serverless simplifies development but requires optimization of cold start problems.

HTML: The Structure, CSS: The Style, JavaScript: The BehaviorHTML: The Structure, CSS: The Style, JavaScript: The BehaviorApr 18, 2025 am 12:09 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML defines the web page structure, 2. CSS controls the web page style, and 3. JavaScript adds dynamic behavior. Together, they build the framework, aesthetics and interactivity of modern websites.

The Future of HTML: Evolution and Trends in Web DesignThe Future of HTML: Evolution and Trends in Web DesignApr 17, 2025 am 12:12 AM

The future of HTML is full of infinite possibilities. 1) New features and standards will include more semantic tags and the popularity of WebComponents. 2) The web design trend will continue to develop towards responsive and accessible design. 3) Performance optimization will improve the user experience through responsive image loading and lazy loading technologies.

HTML vs. CSS vs. JavaScript: A Comparative OverviewHTML vs. CSS vs. JavaScript: A Comparative OverviewApr 16, 2025 am 12:04 AM

The roles of HTML, CSS and JavaScript in web development are: HTML is responsible for content structure, CSS is responsible for style, and JavaScript is responsible for dynamic behavior. 1. HTML defines the web page structure and content through tags to ensure semantics. 2. CSS controls the web page style through selectors and attributes to make it beautiful and easy to read. 3. JavaScript controls web page behavior through scripts to achieve dynamic and interactive functions.

HTML: Is It a Programming Language or Something Else?HTML: Is It a Programming Language or Something Else?Apr 15, 2025 am 12:13 AM

HTMLisnotaprogramminglanguage;itisamarkuplanguage.1)HTMLstructuresandformatswebcontentusingtags.2)ItworkswithCSSforstylingandJavaScriptforinteractivity,enhancingwebdevelopment.

HTML: Building the Structure of Web PagesHTML: Building the Structure of Web PagesApr 14, 2025 am 12:14 AM

HTML is the cornerstone of building web page structure. 1. HTML defines the content structure and semantics, and uses, etc. tags. 2. Provide semantic markers, such as, etc., to improve SEO effect. 3. To realize user interaction through tags, pay attention to form verification. 4. Use advanced elements such as, combined with JavaScript to achieve dynamic effects. 5. Common errors include unclosed labels and unquoted attribute values, and verification tools are required. 6. Optimization strategies include reducing HTTP requests, compressing HTML, using semantic tags, etc.

From Text to Websites: The Power of HTMLFrom Text to Websites: The Power of HTMLApr 13, 2025 am 12:07 AM

HTML is a language used to build web pages, defining web page structure and content through tags and attributes. 1) HTML organizes document structure through tags, such as,. 2) The browser parses HTML to build the DOM and renders the web page. 3) New features of HTML5, such as, enhance multimedia functions. 4) Common errors include unclosed labels and unquoted attribute values. 5) Optimization suggestions include using semantic tags and reducing file size.

Understanding HTML, CSS, and JavaScript: A Beginner's GuideUnderstanding HTML, CSS, and JavaScript: A Beginner's GuideApr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool