Home  >  Article  >  Web Front-end  >  How to implement asynchronous synchronous requests in AJAX

How to implement asynchronous synchronous requests in AJAX

php中世界最好的语言
php中世界最好的语言Original
2017-12-04 13:43:452921browse

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)

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