This commit is contained in:
Ilya Kantor 2019-10-07 13:30:46 +03:00
parent 71ff8f81b0
commit a88e082ef9

View file

@ -24,15 +24,16 @@ To do the request, we need 3 steps:
1. Create `XMLHttpRequest`: 1. Create `XMLHttpRequest`:
```js ```js
let xhr = new XMLHttpRequest(); // the constructor has no arguments let xhr = new XMLHttpRequest();
``` ```
The constructor has no arguments.
2. Initialize it: 2. Initialize it, usually right after `new XMLHttpRequest`:
```js ```js
xhr.open(method, URL, [async, user, password]) xhr.open(method, URL, [async, user, password])
``` ```
This method is usually called right after `new XMLHttpRequest`. It specifies the main parameters of the request: This method specifies the main parameters of the request:
- `method` -- HTTP-method. Usually `"GET"` or `"POST"`. - `method` -- HTTP-method. Usually `"GET"` or `"POST"`.
- `URL` -- the URL to request, a string, can be [URL](info:url) object. - `URL` -- the URL to request, a string, can be [URL](info:url) object.
@ -49,14 +50,14 @@ To do the request, we need 3 steps:
This method opens the connection and sends the request to server. The optional `body` parameter contains the request body. This method opens the connection and sends the request to server. The optional `body` parameter contains the request body.
Some request methods like `GET` do not have a body. And some of them like `POST` use `body` to send the data to the server. We'll see examples later. Some request methods like `GET` do not have a body. And some of them like `POST` use `body` to send the data to the server. We'll see examples of that later.
4. Listen to `xhr` events for response. 4. Listen to `xhr` events for response.
These three are the most widely used: These three events are the most widely used:
- `load` -- when the result is ready, that includes HTTP errors like 404. - `load` -- when the request is complete (even if HTTP status is like 400 or 500), and the response is fully downloaded.
- `error` -- when the request couldn't be made, e.g. network down or invalid URL. - `error` -- when the request couldn't be made, e.g. network down or invalid URL.
- `progress` -- triggers periodically during the download, reports how much downloaded. - `progress` -- triggers periodically while the response is being downloaded, reports how much has been downloaded.
```js ```js
xhr.onload = function() { xhr.onload = function() {