Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does JavaScript make AJAX calls and requests

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces JavaScript how to make AJAX calls and requests related knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe you will get something after reading this JavaScript how to make AJAX calls and requests, let's take a look.

1.AJAX

The term AJAX refers to asynchronous JavaScript and XML.

AJAX is used in JS to make asynchronous network requests to obtain resources. Of course, unlike what the name implies, resources are not limited to XML, but are also used to obtain resources such as JSON, HTML, or plain text.

2.XMLHttpRequest

The XMLHttpRequest object (XHR for short) was used to retrieve data asynchronously from the server in the early days.

XML is used because it is first used to retrieve XML data. Now, it can also be used to retrieve JSON, HTML or plain text.

Case 2.1: GET

Function success () {var data = JSON.parse (this.responseText) console.log (data)} function error (err) {console.log ('Error Occurred:', err)} var xhr = new XMLHttpRequest () xhr.onload = successxhr.onerror = errorxhr.open ("GET", "https://jsonplaceholder.typicode.com/posts/1")xhr.send()"

We see that to make a simple GET request, you need two listeners to handle the success and failure of the request. We also need to call the open () and send () methods. The response from the server is stored in the responseText variable, which is converted to a JavaScript object using JSON.parse ().

Function success () {var data = JSON.parse (this.responseText); console.log (data);} function error (err) {console.log ('Error Occurred:', err);} var xhr = new XMLHttpRequest (); xhr.onload = success;xhr.onerror = error;xhr.open ("POST", "https://jsonplaceholder.typicode.com/posts");xhr.setRequestHeader("Content-Type"," application/json; charset=UTF-8 ") Xhr.send (JSON.stringify ({title: 'foo', body:' bar', userId: 1}))

We see that the POST request is similar to the GET request. We need to set the request header "Content-Type" separately using setRequestHeader and send the JSON body as a string using JSON.stringify in the send method.

2.3 XMLHttpRequest vs Fetch

Early developers have been using XMLHttpRequest for years to request data. Modern fetch API allows us to make web requests similar to XMLHttpRequest (XHR). The main difference is that fetch () API uses Promises, which makes API simpler, more concise, and avoids callback hell.

3. Fetch API

Fetch is a native JavaScript API for making AJAX calls. It is supported by most browsers and is now widely used.

3.1 API usage

Fetch (url, options) .then (response = > {/ / handle response data}) .catch (err = > {/ / handle errors})

API parameter

Fetch () API has two parameters

1. Url is a required parameter, and it is the path of the resource you want to obtain.

2. Options is an optional parameter. You do not need to provide this parameter to make a simple GET request.

Method: GET | POST | PUT | DELETE | PATCH

Headers: request header, such as {"Content-type": "application/json; charset=UTF-8"}

Mode: cors | no-cors | same-origin | navigate

Cache: default | reload | no-cache

Body: commonly used for POST requests

API returns a Promise object

Fetch () API returns a promise object.

If there is a network error, it is rejected, which is handled in the .catch () block.

If the response from the server carries any status codes (such as 200,404,500), the promise will be parsed. The response object can be processed in a .then () block.

Error handling

Note that for a successful response, we expect the status code to be 200 (normal), but even if the response has an error status code (for example, 404 (resource not found) and 500 (internal server error), the status of fetch () API is resolved, and we need to deal with those explicitly in the .then () block.

We can see the HTTP status in the response object:

HTTP status code, for example, 200.

Ok-Boolean value, or true if the HTTP status code is 200,299.

3.2 example: GET

Const getTodoItem = fetch ('https://jsonplaceholder.typicode.com/todos/1'). Then (response = > response.json ()) .catch (err = > console.error (err)); getTodoItem.then (response = > console.log (response)); Response {userId: 1, id: 1, title: "delectus aut autem", completed: false}

There are two things to note in the above code:

Fetch API returns a promise object that we can assign to a variable and execute later.

We must also call response.json () to convert the response object to JSON

Error handling

Let's take a look at what happens when HTTP GET requests to throw a 500th error:

Fetch ('http://httpstat.us/500') / / this API throw 500 error. Then (response = > () = > {console.log ("Inside first then block"); return response.json ();}) .then (json = > console.log ("Inside second then block", json)) .catch (err = > console.error ("Inside catch block:", err)); Inside first then block ➤ ⓧ Inside catch block: SyntaxError: Unexpected token I in JSON at position 4

We see that even if API throws the500 error, it still enters the then () block first, where it cannot parse the error JSON and throw the error caught by the catch () block.

This means that if we use fetch () API, we need to explicitly handle such errors like this:-

Fetch ('http://httpstat.us/500'). Then (handleErrors). Then (response = > response.json ()). Then (response = > console.log (response)) .catch (err = > console.error ("Inside catch block:", err)); function handleErrors (response) {if (! response.ok) {/ throw error based on custom conditions on response throw Error (response.statusText);} return response;} ➤ Inside catch block: Error: Internal Server Error at handleErrors (Script snippet% 239)

3.3Example: POST

Fetch ('https://jsonplaceholder.typicode.com/todos', {method:' POST', body: JSON.stringify ({completed: true, title: 'new todo item', userId: 1}), headers: {"Content-type": "application/json" Charset=UTF-8 "}}) .then (response = > response.json ()) .then (json = > console.log (json)) .catch (err = > console.log (err)) Response ➤ {completed: true, title:" new todo item ", userId: 1, id: 201}

There are two things to note in the above code:-

A POST request is similar to a GET request. We also need to send the method,body and headers attributes in the second parameter of fetch () API.

We must use JSON.stringify () to convert the object to a string to request the body parameter

4.Axios API

Axios API is very similar to fetch API, except that it makes some improvements. I personally prefer to use Axios API rather than fetch () API for the following reasons:

Providing axios.get () for GET requests, providing axios.post () for POST requests, and so on, makes our code more concise.

Think of the response code (for example, 404,500) as errors that can be handled in the catch () block, so we don't need to explicitly handle these errors.

It provides backward compatibility with older browsers such as IE11

It returns the response as a JSON object, so we don't need to do any parsing

4.1 example: GET

/ / the method for introducing scripts into the chrome console var script = document.createElement ('script'); script.type =' text/javascript';script.src = 'https://unpkg.com/axios/dist/axios.min.js';document.head.appendChild(script);axios.get('https://jsonplaceholder.typicode.com/todos/1'). Then (response = > console.log (response.data)) .catch (err = > console.error (err)) Response {userId: 1, id: 1, title: "delectus aut autem", completed: false}

As we can see, we use response directly to get the response data. The data does not have any parsing objects, unlike fetch () API.

Error handling

Axios.get ('http://httpstat.us/500'). Then (response = > console.log (response.data)) .catch (err = > console.error ("Inside catch block:", err)); Inside catch block: Error: Network Error

We see that the500 errors are also caught by the catch () block, unlike fetch () API, which we have to deal with explicitly.

4.2 example: POST

Axios.post ('https://jsonplaceholder.typicode.com/todos', {completed: true, title:' new todo item', userId: 1}). Then (response = > console.log (response.data)) .catch (err = > console.log (err)) {completed: true, title: "new todo item", userId: 1, id: 201}

We see that the POST method is very short and can be passed directly to the request body parameters, unlike fetch () API.

This is the end of the article on "how JavaScript makes AJAX calls and requests". Thank you for reading! I believe you all have a certain understanding of "how JavaScript makes AJAX calls and requests". If you want to learn more, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report