Table of Contents
1.AJAX
2. data.
3.1 API usage
4.Axios API
Home Web Front-end JS Tutorial A brief discussion on how to make AJAX calls and requests using JavaScript

A brief discussion on how to make AJAX calls and requests using JavaScript

Jun 23, 2021 pm 12:04 PM
ajax request ajax call javascript

Ajax is a technology used to create better, faster and more interactive web applications. This article will show you how to use JavaScript to make AJAX calls and requests.

A brief discussion on how to make AJAX calls and requests using JavaScript

#In this tutorial, we will learn how to make AJAX calls using JS.

1.AJAX

The term AJAX stands for asynchronous JavaScript and XML.

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

There are multiple ways to make network requests and get data from the server. We will introduce them one by one.

2. data.

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

Example 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 = success
xhr.onerror = error
xhr.open("GET", ""https://jsonplaceholder.typicode.com/posts/1")
xhr.send()
Copy after login

We see that to make a simple GET request, two listeners are needed to handle the request of success and failure. 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
  })
);
Copy after login
We see that POST requests are similar to GET requests. We need to additionally set the request header "Content-Type" 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 many years to request data . The modern fetch API allows us to make network requests similar to XMLHttpRequest (XHR)

. The main difference is that

fetch() API uses Promises, which makes the API simpler and more concise and avoids callback hell. 3. Fetch APIFetch is a native JavaScript API for making AJAX calls. It is supported by most browsers and is now widely used. application.

3.1 API usage

fetch(url, options)
    .then(response => {
        // handle response data
    })
    .catch(err => {
        // handle errors
    });
Copy after login

API parameters

fetch() The API has two parameters

1 and

url

are required parameters, which are the paths to the resources you want to obtain.

2, options

is an optional parameter. There is no need to provide this parameter to make a simple GET request.

method: GET | POST | PUT | DELETE | PATCH

headers: Request headers, such as { “Content-type”: “application/json; charset=UTF-8” }

  • ##mode: cors | no-cors | same-origin | navigate
  • cache: default | reload | no-cache

    body: Generally used for POST requests

    • API returns Promise object
    fetch()
  • The API returns a promise object.

Will reject if there is a network error, which is handled in the .catch()

block.

If the response from the server comes with any status code (such as 200

,
    404
  • , 500), the promise will be resolved. Response objects can be handled in
  • .then()
  • blocks. Error handlingPlease note that for a successful response we expect a status code of 200
  • (normal status), but even The response comes with an error status code (such as
404

(resource not found) and 500 (internal server error)), as is the status of the

fetch()

API #resolved, we need to handle those explicitly in the .then() block. We can see the HTTP status in the response object: HTTP status code, such as 200. ok – Boolean value,

true

if the HTTP status code is 200-299.

  • 3.2 Example: GET
  • <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>const getTodoItem = fetch(&amp;#39;https://jsonplaceholder.typicode.com/todos/1&amp;#39;) .then(response =&gt; response.json()) .catch(err =&gt; console.error(err)); getTodoItem.then(response =&gt; console.log(response));</pre><div class="contentsignin">Copy after login</div></div><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>Response { userId: 1, id: 1, title: &quot;delectus aut autem&quot;, completed: false }</pre><div class="contentsignin">Copy after login</div></div>There are two things to note in the above code:

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

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

  • Error handling
  • Let’s take a look at what happens when an HTTP GET

    request throws a 500 error:
  • fetch(&#39;http://httpstat.us/500&#39;) // 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));
    Copy after login
    Inside first then block
    ➤ ⓧ Inside catch block: SyntaxError: Unexpected token I in JSON at position 4
    Copy after login
We see that even though the API throws a 500 error, It will still first enter the

then() block where it fails to parse the error JSON and throws the error caught by the catch()

block.

This means that if we use the fetch()

API, we need to handle such errors explicitly like this: -

fetch(&#39;http://httpstat.us/500&#39;)
  .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;
}
Copy after login
 ➤ Inside catch block: Error: Internal Server Error at handleErrors (Script snippet %239:9)
Copy after login
3.3 Example: POST

fetch(&#39;https://jsonplaceholder.typicode.com/todos&#39;, {
    method: &#39;POST&#39;,
    body: JSON.stringify({
      completed: true,
      title: &#39;new todo item&#39;,
      userId: 1
    }),
    headers: {
      "Content-type": "application/json; charset=UTF-8"
    }
  })
  .then(response => response.json())
  .then(json => console.log(json))
  .catch(err => console.log(err))
Copy after login
Response
➤ {completed: true, title: "new todo item", userId: 1, id: 201}
Copy after login

在上面的代码中需要注意两件事:-

  • POST请求类似于GET请求。 我们还需要在fetch() API的第二个参数中发送methodbodyheaders 属性。

  • 我们必须需要使用 JSON.stringify() 将对象转成字符串请求body 参数

4.Axios API

Axios API非常类似于fetch API,只是做了一些改进。我个人更喜欢使用Axios API而不是fetch() API,原因如下:

  • 为GET 请求提供 axios.get(),为 POST 请求提供 axios.post()等提供不同的方法,这样使我们的代码更简洁。
  • 将响应代码(例如404、500)视为可以在catch()块中处理的错误,因此我们无需显式处理这些错误。
  • 它提供了与IE11等旧浏览器的向后兼容性
  • 它将响应作为JSON对象返回,因此我们无需进行任何解析

4.1 示例:GET

// 在chrome控制台中引入脚本的方法

var script = document.createElement(&#39;script&#39;);
script.type = &#39;text/javascript&#39;;
script.src = &#39;https://unpkg.com/axios/dist/axios.min.js&#39;;
document.head.appendChild(script);
Copy after login
axios.get(&#39;https://jsonplaceholder.typicode.com/todos/1&#39;)
  .then(response => console.log(response.data))
  .catch(err => console.error(err));
Copy after login
Response
{ userId: 1, id: 1, title: "delectus aut autem", completed: false }
Copy after login

我们可以看到,我们直接使用response获得响应数据。数据没有任何解析对象,不像fetch() API。

错误处理

axios.get(&#39;http://httpstat.us/500&#39;)
  .then(response => console.log(response.data))
  .catch(err => console.error("Inside catch block:", err));
Copy after login
Inside catch block: Error: Network Error
Copy after login

我们看到,500错误也被catch()块捕获,不像fetch() API,我们必须显式处理它们。

4.2 示例:POST

axios.post(&#39;https://jsonplaceholder.typicode.com/todos&#39;, {
      completed: true,
      title: &#39;new todo item&#39;,
      userId: 1
  })
  .then(response => console.log(response.data))
  .catch(err => console.log(err))
Copy after login
 {completed: true, title: "new todo item", userId: 1, id: 201}
Copy after login

我们看到POST方法非常简短,可以直接传递请求主体参数,这与fetch()API不同。

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of A brief discussion on how to make AJAX calls and requests using JavaScript. 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

How to extend the timeout of Ajax requests? How to extend the timeout of Ajax requests? Jan 26, 2024 am 10:09 AM

How to extend the expiration time of Ajax requests? When making network requests, we often encounter situations where we need to process large amounts of data or complex calculations, which may cause the request to time out and fail to return data normally. In order to solve this problem, we can ensure that the request can be completed successfully by extending the expiration time of the Ajax request. The following will introduce some methods and specific code examples to extend the expiration time of Ajax requests. When making an Ajax request using the timeout attribute, you can set the timeout attribute to

See all articles