企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[[MDN-FetchingData](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Fetching_data)] `XHR` has been around for a long time now and has very good cross-browser support. `Fetch` and Promises, on the other hand, are a more recent addition to the web platform, although they're supported well across the browser landscape, with the exception of Internet Explorer. If you need to support older browsers, then an XHR solution might be preferable. If however you are working on a more progressive project and aren't as worried about older browsers, then Fetch could be a good choice. You should really learn both — Fetch will become more popular as Internet Explorer declines in usage (IE is no longer being developed, in favor of Microsoft's new Edge browser), but you might need XHR for a while yet. [TOC] ## Ajax(Asynchronous JavaScript and XML) **AJAX** is a programming practice of building more complex, dynamic webpages using a technology known as `XMLHttpRequest`. The technologies that allow web pages to request small chunks of data (such as `HTML`,`XML`,`JSON`, or plain text) and display them only when needed. What AJAX allows you to do is just update parts of the `DOM` of a `HTML` webpage instead of having to reload the entire page. AJAX also lets you work asynchronously, meaning your code continues to run while that part of your webpage is trying to reload (compared to synchronously which will block your code from running until that part of your webpage is done reloading). With interactive websites and modern web standards, AJAX is gradually being replaced by functions within JavaScript frameworks and the official `Fetch` API Standard. ## XMLHttpRequest `XMLHttpRequest`(which is frequently abbreviated to `XHR`) is a fairly old technology now — it was invented by Microsoft in the late '90s, and has been standardized across browsers for quite a long time. ## Fetch The Fetch API is basically a modern replacement for XHR; it was introduced in browsers recently to make asynchronous HTTP requests easier to do in JavaScript, both for developers and other APIs that build on top of Fetch. `fetch()` returns a [promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) [[MDN-Using Fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch)] example: ~~~ Javascript //code 1 fetch(url).then(function(response) { response.text().then(function(text) { console.log(text); }); }); //code 2 fetch(url).then(function(response) { return response.text() }).then(function(text) { console.log(text); }); //code 3(code 2 的箭头函数版) fetch(url).then(response=>{ return response.text() }).then(text=> { console.log(text); }); ~~~ `fetch(url)`方法是向`url`发起`request`,该方法返回的是向`url`发起`request`后的响应结果;该响应结果是一个`Promise`对象,这个`Promise`对象resolve成一个`response`对象。