Home Web Front-end JS Tutorial How to implement asynchronous synchronous requests in AJAX

How to implement asynchronous synchronous requests in AJAX

Dec 04, 2017 pm 01:43 PM
ajax Synchronize asynchronous

This tutorial is about how to implement asynchronous and synchronous requests in AJAX. We know that the FormData type and event listening interface require AJAX to implement. So is there a way to only request the server when the page data changes? What about dynamically replacing the data displayed on the page with new data while preventing the page from refreshing? Today let’s talk about the concept of AJAX.

XMLHttpRequest object

XMLHttpRequest is just a JavaScript object, to be precise, it is a constructor. In other words, it is not mysterious at all, the only thing special about it is that it is provided by the client (i.e. the browser) (rather than being native to JavaScript), and besides that, it has properties, methods, and needs Instantiating through the new keyword, we only need to master them;

XMLHttpRequest to obtain data

We know that AJAX is used to obtain data in the project by preventing page refresh, then Where does the data come from? How do we know how to obtain this data? The answer is that we usually use APIs to interact with various databases.

"API" is the abbreviation of "Application Programming Interface" (ie: Application Programming Interface). You can imagine that some data is open and waiting to be used, and the way we obtain this data is to use the API . The usual form of an API is a URL, and provides specified parameter names and parameter values ​​to help you locate the data you want to obtain.

XMLHttpRequest to prepare the request

To interact with the server, you first need to think about the following questions:

Do we want to obtain data or store data? ——The request method is "GET" or "POST". Where to send the request?    ——That is, the corresponding API address. How to wait for the response? - There are two options: "synchronous" and "asynchronous"

The .open() method of the XMLHttpRequest instance is used to answer the above three questions. The .open() method receives three parameters: request method, request URL address and a Boolean value of whether it is an asynchronous request.

The following is an example of calling the .open() method:

// This code will initiate a GET synchronous request for "example.php".

xhr.open("get", "example.php", false)

// "DELETE", "HEAD", "OPTONS", "PUT" can also be used as open( ) first parameter of the method.

In the above code, synchronization is achieved by passing the third parameter as false. It should be noted that once set to synchronous, the send() method will block until the request is completed.

(3) Synchronous requests and asynchronous requests

People usually think that AJAX is asynchronous, but in fact it is not. AJAX is a technology to avoid refreshing the page after getting the data. As for waiting for the server Whether the response method is synchronous or asynchronous requires developers to configure it based on business needs (although it is usually asynchronous).

You may be curious, when do we need to use synchronous AJAX? From my personal experience, it seems difficult to find the corresponding scene.

Finally, let’s briefly explain the difference between “synchronous” waiting for a response and “asynchronous” waiting for a response: “Synchronous” means that once the request is sent, any subsequent JavaScript code will not be executed, while “asynchronous” means When the request is issued, subsequent JavaScript code will continue to execute. When the request is successful, the corresponding callback function will be called.

XMLHttpRequest Level 2 FormData Type

The W3C has proposed the XMLHttpRequest Level 2 specification. Although not all browsers have implemented the content stipulated in the specification, there are still some contents that are all or Implemented by most browsers.

FormData type

FormData is a new data type (constructor) provided by XMLHttpRequest level 2. Remember how to disguise a POST requestSubmit for a form? FormData makes this process easier because the XHR2 object recognizes that the data type passed in is an instance of FormData and automatically configures the appropriate header information.

How to disguise a POST request as a form submission?

When using the POST method to submit form data in this sequence, the "Content-Type" request header must be set to this value.

xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

Note: This is not a required value when using form, because this is Default method.

FormData is used as follows:

// 添加数据
let data1 = new FormData()
data1.append("name", "Tom")
xhr.send(data1)
 
// 提取表单数据
let data2 = new FormData(document.forms[0])
xhr.send(data2)
Copy after login

In addition, another benefit of FormData is that compared to traditional AJAX requests, it allows us to upload binary data (images, videos, audio wait).

Browser compatibility of FormData.

Desktop IE 10+ and other browsers are supported

Mobile Android, Firefox Mobile, OperaMobile are supported, other browsers are unknown

XMLHttpRequest level 2 event monitoring interface

The first version of XMLHttpRequest can only specify a callback function for the onreadystatechange event. The event responds to all situations.

The second version of XMLHttpRequest allows specifying callback functions for more events.

onloadstart Request issued

onprogress Sending and loading data

onabort The request was aborted, for example, the user called the abort() method

onerror Request failed

onload    The request is completed successfully

ontimeout   The time limit specified by the user has expired and the request has not been completed.

onloadend    The request is completed, regardless of the result or failure


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

Related reading:

Summary of the front-end js framework and explanation of its uses

How to solve the problem of ajax unit when parsing json data In the form of seconds

The implementation steps of js and servlet to implement file upload in h5

The above is the detailed content of How to implement asynchronous synchronous requests in 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

One or more items in the folder you synced do not match Outlook error One or more items in the folder you synced do not match Outlook error Mar 18, 2024 am 09:46 AM

When you find that one or more items in your sync folder do not match the error message in Outlook, it may be because you updated or canceled meeting items. In this case, you will see an error message saying that your local version of the data conflicts with the remote copy. This situation usually happens in Outlook desktop application. One or more items in the folder you synced do not match. To resolve the conflict, open the projects and try the operation again. Fix One or more items in synced folders do not match Outlook error In Outlook desktop version, you may encounter issues when local calendar items conflict with the server copy. Fortunately, though, there are some simple ways to help

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

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

How to solve the problem of jQuery AJAX error 403? How to solve the problem of jQuery AJAX error 403? Feb 23, 2024 pm 04:27 PM

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

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.

Advanced Guide to Python asyncio: From Beginner to Expert Advanced Guide to Python asyncio: From Beginner to Expert Mar 04, 2024 am 09:43 AM

Concurrent and Asynchronous Programming Concurrent programming deals with multiple tasks executing simultaneously, asynchronous programming is a type of concurrent programming in which tasks do not block threads. asyncio is a library for asynchronous programming in python, which allows programs to perform I/O operations without blocking the main thread. Event loop The core of asyncio is the event loop, which monitors I/O events and schedules corresponding tasks. When a coroutine is ready, the event loop executes it until it waits for I/O operations. It then pauses the coroutine and continues executing other coroutines. Coroutines Coroutines are functions that can pause and resume execution. The asyncdef keyword is used to create coroutines. The coroutine uses the await keyword to wait for the I/O operation to complete. The following basics of asyncio

PHP vs. Ajax: Solutions for creating dynamically loaded content PHP vs. Ajax: Solutions for creating dynamically loaded content Jun 06, 2024 pm 01:12 PM

Ajax (Asynchronous JavaScript and XML) allows adding dynamic content without reloading the page. Using PHP and Ajax, you can dynamically load a product list: HTML creates a page with a container element, and the Ajax request adds the data to that element after loading it. JavaScript uses Ajax to send a request to the server through XMLHttpRequest to obtain product data in JSON format from the server. PHP uses MySQL to query product data from the database and encode it into JSON format. JavaScript parses the JSON data and displays it in the page container. Clicking the button triggers an Ajax request to load the product list.

See all articles