search
HomeWeb Front-endJS TutorialA brief discussion on how to make AJAX calls and requests using 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()

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
  })
);
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
    });

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
  • <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><pre class='brush:php;toolbar:false;'>Response { userId: 1, id: 1, title: &quot;delectus aut autem&quot;, completed: false }</pre>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));
    Inside first then block
    ➤ ⓧ Inside catch block: SyntaxError: Unexpected token I in JSON at position 4
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;
}
 ➤ Inside catch block: Error: Internal Server Error at handleErrors (Script snippet %239:9)
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))
Response
➤ {completed: true, title: "new todo item", userId: 1, id: 201}

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

  • 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);
axios.get(&#39;https://jsonplaceholder.typicode.com/todos/1&#39;)
  .then(response => console.log(response.data))
  .catch(err => console.error(err));
Response
{ userId: 1, id: 1, title: "delectus aut autem", completed: false }

我们可以看到,我们直接使用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));
Inside catch block: Error: Network Error

我们看到,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))
 {completed: true, title: "new todo item", userId: 1, id: 201}

我们看到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
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

See all articles

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment