Home > Web Front-end > JS Tutorial > XMLHttpRequest vs the Fetch API for Ajax

XMLHttpRequest vs the Fetch API for Ajax

Christopher Nolan
Release: 2025-02-14 09:33:12
Original
675 people have browsed it

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template