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:
- Probably JavaScript, although VBScript and Flash are also optional.
- 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 http://www.miracleart.cn/link/f589a241141007eb225cd68eed7bc06c:
let xhr = new XMLHttpRequest(); xhr.open('GET', 'http://www.miracleart.cn/link/f589a241141007eb225cd68eed7bc06c'); // 請(qǐng)求狀態(tài)更改事件 xhr.onreadystatechange = function() { // 請(qǐng)求完成? if (xhr.readyState !== 4) return; if (xhr.status === 200) { // 請(qǐng)求成功 - 顯示響應(yīng) console.log(xhr.responseText); } else { // 請(qǐng)求錯(cuò)誤 console.log('HTTP error', xhr.status, xhr.statusText); } }; // 開始請(qǐng)求 xhr.send();
The XMLHttpRequest object has many other options, event, and response properties. For example, timeouts in milliseconds can be set and detected:
// 設(shè)置超時(shí) xhr.timeout = 3000; // 3 秒 xhr.ontimeout = () => console.log('timeout', xhr.responseURL);
Progress events can report long-running file uploads:
// 上傳進(jìn)度 xhr.upload.onprogress = p => { console.log( Math.round((p.loaded / p.total) * 100) + '%') ; };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('http://www.miracleart.cn/link/f589a241141007eb225cd68eed7bc06c') .done(data => console.log(data)) .fail((xhr, status) => console.log('error:', status));
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( 'http://www.miracleart.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...
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( 'http://www.miracleart.cn/link/f589a241141007eb225cd68eed7bc06c', { method: 'GET', credentials: 'same-origin' } )
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:
// 帶有超時(shí)的 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))
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', 'http://www.miracleart.cn/link/f589a241141007eb225cd68eed7bc06c'); // 請(qǐng)求狀態(tài)更改事件 xhr.onreadystatechange = function() { // 請(qǐng)求完成? if (xhr.readyState !== 4) return; if (xhr.status === 200) { // 請(qǐng)求成功 - 顯示響應(yīng) console.log(xhr.responseText); } else { // 請(qǐng)求錯(cuò)誤 console.log('HTTP error', xhr.status, xhr.statusText); } }; // 開始請(qǐng)求 xhr.send();
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Java and JavaScript are different programming languages, each suitable for different application scenarios. Java is used for large enterprise and mobile application development, while JavaScript is mainly used for web page development.

JavaScriptcommentsareessentialformaintaining,reading,andguidingcodeexecution.1)Single-linecommentsareusedforquickexplanations.2)Multi-linecommentsexplaincomplexlogicorprovidedetaileddocumentation.3)Inlinecommentsclarifyspecificpartsofcode.Bestpractic

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

JavaScriptispreferredforwebdevelopment,whileJavaisbetterforlarge-scalebackendsystemsandAndroidapps.1)JavaScriptexcelsincreatinginteractivewebexperienceswithitsdynamicnatureandDOMmanipulation.2)Javaoffersstrongtypingandobject-orientedfeatures,idealfor

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

JavaScripthassevenfundamentaldatatypes:number,string,boolean,undefined,null,object,andsymbol.1)Numbersuseadouble-precisionformat,usefulforwidevaluerangesbutbecautiouswithfloating-pointarithmetic.2)Stringsareimmutable,useefficientconcatenationmethodsf

If JavaScript applications load slowly and have poor performance, the problem is that the payload is too large. Solutions include: 1. Use code splitting (CodeSplitting), split the large bundle into multiple small files through React.lazy() or build tools, and load it as needed to reduce the first download; 2. Remove unused code (TreeShaking), use the ES6 module mechanism to clear "dead code" to ensure that the introduced libraries support this feature; 3. Compress and merge resource files, enable Gzip/Brotli and Terser to compress JS, reasonably merge files and optimize static resources; 4. Replace heavy-duty dependencies and choose lightweight libraries such as day.js and fetch
