Core points
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.
AJAX is the abbreviation for asynchronous JavaScript and XML. "Async" is definitely correct, but:
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).
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();
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);
Progress events can report long-running file uploads:
// 上传进度 xhr.upload.onprogress = p => { console.log( Math.round((p.loaded / p.total) * 100) + '%') ; };
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));
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) );
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...
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.
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' } )
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.
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); }); }
…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))
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();
Fetch can be aborted by calling controller.abort(); Promise will be rejected, so the .catch() function will be called.
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.
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.
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.
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.
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.
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.
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".
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.
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.
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.
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.
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!