首頁 >web前端 >js教程 >✅fetch 和 XMLHTTPRequest 有什麼不同?

✅fetch 和 XMLHTTPRequest 有什麼不同?

Barbara Streisand
Barbara Streisand原創
2024-11-15 13:22:02505瀏覽

大家好!在從事一個有趣的專案時,我有一個想法來講述 fetch 和 XMLHTTPRequest 之間的差異。事實上,如果你知道它的創建歷史,這個問題聽起來很有趣,從某種意義上說,它有點不正確,但你仍然需要了解它,因為,比方說,對於我作為一個開發人員來說,當我處理每天都會遇到各種各樣的API,了解一下會很有用,以免創建不必要的程式碼。

什麼是 XMLHTTPRequest 及其建立簡史

在 javascript 中,XMLHttpRequest 物件用於與伺服器互動。您可以從 URL 檢索數據,而無需刷新整個頁面。這使得網頁能夠僅更新頁面的一部分,而不會中斷使用者正在做的事情。但總的來說,說穿了就是一個API。當我們聽到這個時,我們立即想起事件循環、非同步(程式碼執行將在一定時間後完成)等概念。例如,使用 XMLHTTPRequest 的程式碼如下所示:

const xhr = new XMLHttpRequest();
// method, URL, [isAsync, user, password]
xhr.open("GET", "/api/getPage");
// body
xhr.send()

XMLHTTPRequest 本身的創建歷史讓我們回到了恐龍行走的遙遠歲月……好吧,開個玩笑。事實上,這個 API 最初是由 Microsoft 開發的,並在 Microsoft Exchange Server 軟體 2000 產品的 Outlook on the Web 元件中引進。

✅What is the difference between fetch and XMLHTTPRequest?

當時,它的名稱有所不同 - IXMLHTTPRequest,並且在介面的第一個版本中(如果可以這麼說的話)與現在有點不同。也就是說,基數明顯保持不變,但25年來明顯進行了調整。後來,它被添加到 MSXML 2.0 中,甚至後來在 1999 年 3 月添加到 Internet Explorer 5 中。

然後,Mozilla 程式設計師基於 IXMLHTTPRequest 開發了自己的 API 版本,然後稱為 nsIXMLHttpRequest,並使其可以透過我們喜愛的 XMLHttpRequest 進行存取。所有這些都在 2000 年 12 月添加到 Gecko 0.6 版本中(Gecko 是 FireFox 和許多其他地方使用的瀏覽器引擎)。當時還沒有FireFox這樣的東西,因為它的第一個版本在2002年9月發布,被稱為Phoenix,然後是FireBird,直到2004年才被稱為FireFox。然後,在這一切之前,出現了 Netscape Navigator,但與 Internet Explorer 的對抗僅此而已 - 那是另一個故事,在本文中沒有必要寫。後來又增加了對Safari、Opera等瀏覽器的支援。因此,當人們告訴你這個物件是用來相容舊瀏覽器時,那麼他們當然是對的,因為這把我們帶到了 90 年代末,當時 Web 開發剛剛發展起來。你甚至可以記得網路泡沫的時間,但是,不可否認,那是早一點,或者是在那個時候(如果我們使用 Internet Explorer),但無論如何,那是那時。

So what's the difference?

So, returning to the question about the difference, the most important difference is already hidden in history, because XMLHTTPRequest is just an old, but supported API, and fetch is just a new API, which kind of replaces it. As of today, XMLHTTPRequest 2.0 was released in January 2012, but the latest edition of 1.0 standard was released in December of the same year. This is the current standard for this object. But now imagine the faces of the developers who wrote this all the time:

var xhr = new XMLHttpRequest();
xhr.open('GET', '/api/getData', true);

xhr.onload = function () {
    if (xhr.status >= 200 && xhr.status < 300) {
        var data = JSON.parse(xhr.responseText);
        console.log(data);
    } else {
        console.error('Request failed with status:', xhr.status);
    }
};

xhr.onerror = function () {
    console.error('There was a network error.');
};

xhr.send();

instead of this

fetch('/api/getData')
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })
    .then(data => {
        console.log(data);
    })
    .catch(error => {
        console.error('There was a problem with the fetch operation:', error);
    });

a few years ago. That's the only thing that comes to mind right away.

✅What is the difference between fetch and XMLHTTPRequest?

But seriously, here is a short list of differences:

  1. Promise-oriented: The Fetch API uses promises, which makes it easier to work with asynchronous code and allows you to use convenient constructs like .then() and async and await.

  2. Simplified interface: The Fetch API has a simpler and more intuitive syntax. For example, to make requests, you don’t need to create an object and set its properties, as is the case with XHR.

  3. Support for new features: The Fetch API supports new features such as Request and Response objects, which provide convenient methods for working with requests, responses, and their transformations.

  4. Support for streams: The Fetch API supports streaming data, which allows you to work with large amounts of data as it is received.

  5. Canceling requests: Although the Fetch API does not have built-in support for canceling requests, you can use the abort controller to do so, which makes managing requests more flexible.

  6. Improved customization: The Fetch API provides more options for configuring requests, such as setting headers, caching modes, and other parameters.

  7. cors support: The Fetch API provides more flexibility in working with CORS (Cross-Origin Resource Sharing), which allows for more flexible configuration of requests to resources from other domains.

  8. Better error handling: When working with the Fetch API, you can better handle response statuses, since a request error (e.g. network unavailable) will reject the promise, while a successful response with a 4xx or 5xx code will not reject it, and you will need to check the status code yourself.

✅What is the difference between fetch and XMLHTTPRequest?
This is of course not me, but it's just a cool picture

물론 더 많은 차이점이 있지만 지금 나열하는 것은 의미가 없습니다. 왜냐하면 모든 매개변수로 볼 때 이것은 단순히 최신 브라우저 요구 사항에 대한 이전 표준의 향상된 버전일 뿐이라는 것이 분명하기 때문입니다.

후문

처음에는 가져오기가 새로운 표준인 한 줄을 작성하려고 생각했지만 실제로는 말할 수 있는 멋진 내용이 많이 있는데 너무 단순하고 유익하지 않을 것입니다. 가져오기에 관한 전체 기사를 작성할 수 있지만 이 기사에는 특별한 요점이 없습니다. 하지만 제 생각에는 전반적으로 모든 것이 괜찮아 보입니다.

글을 읽어주셔서 진심으로 감사드립니다!

추신

그런데 이번 프로젝트는 HMPL이었습니다. 서버에서 클라이언트로 UI를 표시하기 위한 작은 템플릿 언어입니다. 이 프로젝트를 별점으로 평가해 주시면 좋을 것 같습니다. 감사합니다!

스타HMPL

以上是✅fetch 和 XMLHTTPRequest 有什麼不同?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn