Table of Contents
From AJAX to Ajax
In-depth understanding of XMLHttpRequest
Quick Learn about Fetch
Browser support
Cookies are not included by default
Errors will not be rejected
Timeout is not supported
Abort Fetch
No progress
XMLHttpRequest with Fetch API?
FAQs (FAQs) about XMLHttpRequest and Fetch APIs
What are the main differences between XMLHttpRequest and Fetch API?
Is the Fetch API better than XMLHttpRequest?
Can the Fetch API replace XMLHttpRequest?
What are the advantages of using the Fetch API?
What are the disadvantages of using the Fetch API?
What are the advantages of using XMLHttpRequest?
What are the disadvantages of using XMLHttpRequest?
How to choose XMLHttpRequest and Fetch API?
Can I use both XMLHttpRequest and Fetch API in the same project?
Is there any alternative XMLHttpRequest and Fetch APIs to make HTTP requests in JavaScript?
Home Web Front-end JS Tutorial XMLHttpRequest vs the Fetch API for Ajax

XMLHttpRequest vs the Fetch API for Ajax

Feb 14, 2025 am 09:33 AM

XMLHttpRequest vs the Fetch API for Ajax

Core points

  • In JavaScript, both the Fetch API and XMLHttpRequest are used to make HTTP requests, but the Fetch API is generally considered more powerful and flexible because it uses Promise, which simplifies code and error handling. However, not all browsers support the Fetch API, especially older browsers.
  • XMLHttpRequest Although older and more complex due to the lack of Promise, it is widely supported in all browsers and sends cookies by default, which is useful for server requests that require cookies to authenticate.
  • Fetch API is not a complete replacement for Ajax technology, as it does not support all XHR features and some options can be cumbersome. It also does not support timeouts, making the implementation of error capture more complex.
  • Although the Fetch API has its limitations, it is the future direction for making HTTP requests in JavaScript. However, because of its relatively new and ever-changing, developers should use it with caution in the coming years.

Comparison of trade-offs between XMLHttpRequest and Fetch API

This article will compare the pros and cons of XMLHttpRequest and its modern Ajax implementation of the Fetch API. March 2019 marks Ajax’s 20th anniversary (to some extent). The first implementation of XMLHttpRequest was released in 1999 as an ActiveX component for IE5.0 (don't ask). Before this, there were also ways to extract data from the server without doing a full page refresh, but they often rely on clumsy techniques such as injection or third-party plugins. The main purpose of Microsoft's development of XMLHttpRequest is to provide an alternative to its browser-based Outlook mail client.

XMLHttpRequest was not the web standard until 2006, but it has been implemented in most browsers. Its adoption in Gmail (2004) and Google Maps (2005) led to Jesse James Garrett's article "AJAX: A New Approach to Web Applications" in 2005. This new term makes developers more focused.

From AJAX to Ajax

AJAX is the abbreviation for asynchronous JavaScript and XML. "Async" is definitely correct, but:

  1. Probably JavaScript, although VBScript and Flash are also optional.
  2. The payload does not need to be XML, although XML was very popular at the time. Any data format can be used, and nowadays, JSON is usually preferred.

We now use "Ajax" as a general term for any client process that generally refers to any client process that gets data from the server and updates the DOM dynamically without having to perform full page refresh. Ajax is the core technology of most web applications and single page applications (SPAs).

In-depth understanding of XMLHttpRequest

The following JavaScript code shows the use of XMLHttpRequest (usually abbreviated as XHR) to issue a basic HTTP GET request for https://www.php.cn/link/f589a241141007eb225cd68eed7bc06c:

let xhr = new XMLHttpRequest();
xhr.open('GET', 'https://www.php.cn/link/f589a241141007eb225cd68eed7bc06c');

// 请求状态更改事件
xhr.onreadystatechange = function() {

  // 请求完成?
  if (xhr.readyState !== 4) return;

  if (xhr.status === 200) {
    // 请求成功 - 显示响应
    console.log(xhr.responseText);
  }
  else {
    // 请求错误
    console.log('HTTP error', xhr.status, xhr.statusText);
  }
};

// 开始请求
xhr.send();
Copy after login
Copy after login

The XMLHttpRequest object has many other options, event, and response properties. For example, timeouts in milliseconds can be set and detected:

// 设置超时
xhr.timeout = 3000; // 3 秒
xhr.ontimeout = () => console.log('timeout', xhr.responseURL);
Copy after login

Progress events can report long-running file uploads:

// 上传进度
xhr.upload.onprogress = p => {
  console.log( Math.round((p.loaded / p.total) * 100) + '%') ;
};
Copy after login
The number of options in

can be dazzling, and there are some cross-browser inconsistencies in earlier versions of XMLHttpRequest. Therefore, most libraries and frameworks provide Ajax wrapper functions to handle complexity, such as the jQuery.ajax() method:

// jQuery Ajax
$.ajax('https://www.php.cn/link/f589a241141007eb225cd68eed7bc06c')
  .done(data => console.log(data))
  .fail((xhr, status) => console.log('error:', status));
Copy after login

Quick Learn about Fetch

Fetch API is a modern alternative to XMLHttpRequest. The common Headers, Request, and Response interfaces provide consistency, while Promise allows easier chaining and async/await without callbacks. The XHR example above can be converted to simpler Fetch-based code, which can even parse the returned JSON:

fetch(
    'https://www.php.cn/link/f589a241141007eb225cd68eed7bc06c',
    { method: 'GET' }
  )
  .then( response => response.json() )
  .then( json => console.log(json) )
  .catch( error => console.error('error:', error) );
Copy after login

Fetch is simple, elegant, easy to understand and widely used in PWA service workers. Why not use it instead of the ancient XMLHttpRequest?

Unfortunately, web development is never that simple. Fetch has not completely replaced Ajax technology...

Browser support

Fetch API is supported quite well, but fails in all versions of Internet Explorer. Users using Chrome, Firefox, and Safari versions prior to 2017 may also experience problems. These users may only make up a small part of your user base…or it may be a major customer. Be sure to check before starting coding!

In addition, the Fetch API is relatively new and receives more continuous changes than mature XHR objects. These updates are unlikely to break the code, but some maintenance is expected to be required in the coming years.

Cookies are not included by default

Unlike XMLHttpRequest, not all Fetch implementations send cookies, so your application's authentication may fail. This problem can be solved by changing the initialization options passed in the second parameter, for example:

fetch(
    'https://www.php.cn/link/f589a241141007eb225cd68eed7bc06c',
    {
      method: 'GET',
      credentials: 'same-origin'
    }
  )
Copy after login

Errors will not be rejected

Surprisingly, HTTP errors (such as 404 page not found or 500 internal server error) do not cause Fetch Promise to be denied; .catch() never runs. It usually parses and sets the response.ok status to false.

Discount occurs only if the request cannot be completed (such as a network failure). This can make the implementation of error capture more complex.

Timeout is not supported

Fetch does not support timeouts, and the request will last the browser selected time. Further code is required to wrap the Fetch in another Promise, for example:

// 带有超时的 fetch
function fetchTimeout(url, init, timeout = 3000) {
  return new Promise((resolve, reject) => {
    fetch(url, init)
      .then(resolve)
      .catch(reject);
    setTimeout(reject, timeout);
  });
}
Copy after login

…or maybe use Promise.race(), which parses when fetch or timeout is completed first, for example:

Promise.race([
  fetch('http://url', { method: 'GET' }),
  new Promise(resolve => setTimeout(resolve, 3000))
])
  .then(response => console.log(response))
Copy after login

Abort Fetch

XHR requests can be easily ended using xhr.abort() and if needed, the xhr.onabort function can be used to detect such events.

For years, aborting Fetch was impossible, but it is now supported in browsers that implement the AbortController API. This triggers a signal that can be passed to the Fetch initialization object:

let xhr = new XMLHttpRequest();
xhr.open('GET', 'https://www.php.cn/link/f589a241141007eb225cd68eed7bc06c');

// 请求状态更改事件
xhr.onreadystatechange = function() {

  // 请求完成?
  if (xhr.readyState !== 4) return;

  if (xhr.status === 200) {
    // 请求成功 - 显示响应
    console.log(xhr.responseText);
  }
  else {
    // 请求错误
    console.log('HTTP error', xhr.status, xhr.statusText);
  }
};

// 开始请求
xhr.send();
Copy after login
Copy after login

Fetch can be aborted by calling controller.abort(); Promise will be rejected, so the .catch() function will be called.

No progress

At the time of writing, Fetch does not support progress events. Therefore, the status of file uploads or similar large form submissions cannot be reported.

XMLHttpRequest with Fetch API?

End of the time, the choice is on you...Unless your application has an IE client that needs to upload a progress bar.

For simpler Ajax calls, XMLHttpRequest is lower-level, more complex, and you will need to wrap the function. Unfortunately, once you start thinking about the complexity of timeouts, call aborts, and error capture, Fetch also needs to wrap the functions.

You can choose a Fetch polyfill that is used in conjunction with the Promise polyfill, so you can write Fetch code in IE. However, XHR is used as a fallback; not every option works as expected, for example, cookies are sent regardless of settings.

Fetch is the future. However, the API is relatively new, it does not offer all XHR features, and some options are cumbersome. Use it with caution in the coming years.

FAQs (FAQs) about XMLHttpRequest and Fetch APIs

What are the main differences between XMLHttpRequest and Fetch API?

XMLHttpRequest and Fetch API are both used to make HTTP requests in JavaScript. However, they differ in several ways. The Fetch API is a newer technology that is considered to be more powerful and flexible. It returns a Promise that resolves to the request, whether it succeeds or not. Fetch also provides common definitions of Request and Response objects. On the other hand, XMLHttpRequest is older and does not use Promise, which may make the code more complex and difficult to maintain. It does not have a common definition for Request and Response objects.

Is the Fetch API better than XMLHttpRequest?

Fetch API is often considered a better choice for making HTTP requests in JavaScript due to the use of Promise. Promise makes the code more concise, easier to read, and also makes error handling easier. The functionality of the Fetch API is also more powerful and flexible than XMLHttpRequest. However, XMLHttpRequest is still widely used and supported and may be a better choice in some cases, such as when you need to support older browsers that do not support the Fetch API.

Can the Fetch API replace XMLHttpRequest?

Yes, the Fetch API can replace the XMLHttpRequest in JavaScript that is used to make HTTP requests. The Fetch API is a newer technology and has a more powerful and flexible feature set. It uses Promise, which makes the code more concise, easier to read, and also makes error handling easier. However, XMLHttpRequest is still widely used and supported and may be a better choice in some cases, such as when you need to support older browsers that do not support the Fetch API.

What are the advantages of using the Fetch API?

Fetch API has several advantages over XMLHttpRequest. It uses Promise, which makes the code more concise, easier to read, and also makes error handling easier. The Fetch API also has a more powerful and flexible feature set, including common definitions of Request and Response objects. It also allows you to make requests to other sources, while XMLHttpRequest does not.

What are the disadvantages of using the Fetch API?

One of the main drawbacks of using the Fetch API is that not all browsers support it. In particular, older browsers may not support the Fetch API. In these cases, you may need to use XMLHttpRequest or polyfill. Another disadvantage is that the Fetch API does not send cookies by default, so if you want to send cookies, you need to manually set the credentials option to "include".

What are the advantages of using XMLHttpRequest?

XMLHttpRequest is a proven technology for making HTTP requests in JavaScript. It is widely supported and can be used in all browsers. Unlike the Fetch API, XMLHttpRequest also sends cookies by default. This can be an advantage in some cases, such as when you make a request to a server that requires cookies to authenticate.

What are the disadvantages of using XMLHttpRequest?

XMLHttpRequest does not use Promise, which may make the code more complex and difficult to maintain. It also does not have a common definition of Request and Response objects and does not allow you to make requests to other sources. XMLHttpRequest is also considered a bit outdated compared to newer technologies such as the Fetch API.

How to choose XMLHttpRequest and Fetch API?

Selecting XMLHttpRequest and Fetch APIs depends on your specific needs and the browser you need to support. If you need to support older browsers that do not support the Fetch API, XMLHttpRequest may be a better choice. However, if you are using a newer browser and want to take advantage of the Fetch API's cleaner, more modern syntax and a more powerful and flexible feature set, the Fetch API will be a better choice.

Can I use both XMLHttpRequest and Fetch API in the same project?

Yes, you can use both XMLHttpRequest and Fetch APIs in the same project. You can choose to use XMLHttpRequest for certain tasks and Fetch API for other tasks based on your specific needs and the browser you need to support. However, it is often recommended to stick to one of these for consistency and ease of maintenance.

Is there any alternative XMLHttpRequest and Fetch APIs to make HTTP requests in JavaScript?

Yes, there are several alternatives to XMLHttpRequest and Fetch APIs for making HTTP requests in JavaScript. These include libraries such as Axios, jQuery's $.ajax, and SuperAgent. These libraries provide a higher level of interfaces to make HTTP requests and provide additional features and conveniences compared to XMLHttpRequest and Fetch APIs.

The above is the detailed content of XMLHttpRequest vs the Fetch API for Ajax. 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)

Hot Topics

Java Tutorial
1659
14
PHP Tutorial
1257
29
C# Tutorial
1231
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles