亚洲中字慕日产2020,大陆极品少妇内射AAAAAA,无码av大香线蕉伊人久久,久久精品国产亚洲av麻豆网站

資訊專欄INFORMATION COLUMN

Fetch API

princekin / 1570人閱讀

摘要:現(xiàn)在有很多優(yōu)雅的包裝,但是這遠遠不夠。一個實例代表了一個的請求部分。一旦創(chuàng)建,它所有的屬性都是只讀的。處理基本的返回不是所有的接口都返回格式的數(shù)據(jù),所以還要處理一些類型的返回結(jié)果。最后很好用,但是現(xiàn)在還不允許取消一個請求。

Fetch API

一個隱藏最深的秘密就是AJAX的實現(xiàn)底層的XMLHttpRequest,這個方法本來并不是造出來干這事的?,F(xiàn)在有很多優(yōu)雅的API包裝XHR,但是這遠遠不夠。于是有了fetch API。我們來看看這個API的基本用法。最新的瀏覽器都已經(jīng)支持這個方法了。

XMLHttpRequest

XHR對于我來說太過復(fù)雜,用起來大概是這樣的:

// 開始XHR這些
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
  request = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
  try {
    request = new ActiveXObject("Msxml2.XMLHTTP");
  } 
  catch (e) {
    try {
      request = new ActiveXObject("Microsoft.XMLHTTP");
    } 
    catch (e) {}
  }
}

// 發(fā)送請求.
request.open("GET", "https://davidwalsh.name/ajax-endpoint", true);
request.send(null);

當(dāng)然我們的JavaScript框架可以讓我們愿意去用XHR,但是你看到的只是一個簡單的例子。

基本的Fetch用法

fetch方法可以在window作用域中找到。第一個參數(shù)是你要訪問的URL:

fetch("https://davidwalsh.name/some/url", {
    method: "get"
}).then(function(response) {
    
}).catch(function(err) {
    // Error :(
});

fetch會返回一個Promise作為結(jié)果:

// 簡單的返回結(jié)果處理
fetch("https://davidwalsh.name/some/url").then(function(response) {
    
}).catch(function(err) {
    // Error :(
});

// 更高級的鏈?zhǔn)教幚?fetch("https://davidwalsh.name/some/url").then(function(response) {
    return //...
}).then(function(returnedValue) {
    // ...
}).catch(function(err) {
    // Error :(
});
Request頭

請求能不能靈活使用就在于是否能靈活的設(shè)置請求的頭??梢允褂?b>new Headers():

// 創(chuàng)建一個空的Headers實例
var headers = new Headers();

// 添加內(nèi)容
headers.append("Content-Type", "text/plain");
headers.append("X-My-Custom-Header", "CustomValue");

// 檢查Headers的值
headers.has("Content-Type"); // true
headers.get("Content-Type"); // "text/plain"
headers.set("Content-Type", "application/json");

// 刪除一個Header
headers.delete("X-My-Custom-Header");

// 添加初始值
var headers = new Headers({
    "Content-Type": "text/plain",
    "X-My-Custom-Header": "CustomValue"
});

你可以使用append, has, get, setdelete方法來設(shè)置請求的頭。要使用Request頭,需要創(chuàng)建一個Request實例:

var request = new Request("https://davidwalsh.name/some-url", {
    headers: new Headers({
        "Content-Type": "text/plain"
    })
});

fetch(request).then(function() { /* handle response */ });

我們來看看ResponseRequest都可以做什么。

Request

一個Request實例代表了一個fetch的請求部分。給fetch 傳入一個request你可以發(fā)出高級的、定制的請求:

method - GET, POST, PUT, DELETE, HEAD

url - URL of the request

headers - associated Headers object

referrer - referrer of the request

mode - cors, no-cors, same-origin

credentials - should cookies go with the request? omit, same-origin

redirect - follow, error, manual

integrity - subresource integrity value

cache - cache mode (default, reload, no-cache)

一個簡單的Request看起來是這樣的:

var request = new Request("https://davidwalsh.name/users.json", {
    method: "POST", 
    mode: "cors", 
    redirect: "follow",
    headers: new Headers({
        "Content-Type": "text/plain"
    })
});

// 用起來
fetch(request).then(function() { /* handle response */ });

只有第一個參數(shù),請求的URL,是必須的。一旦Request創(chuàng)建,它所有的屬性都是只讀的。需要注意的是Request有一個clone方法,這個方法在Worker API里使用fetch 的時候很有用。fetch的簡化調(diào)用方法:

fetch("https://davidwalsh.name/users.json", {
    method: "POST", 
    mode: "cors", 
    redirect: "follow",
    headers: new Headers({
        "Content-Type": "text/plain"
    })
}).then(function() { /* handle response */ });
Respone

使用fetch的then方法會獲得一個Response實例。你也可以自己創(chuàng)建一個。

type - basic, cors

url

useFinalURL - Boolean for if url is the final URL

status - status code (ex: 200, 404, etc.)

ok - Boolean for successful response (status in the range 200-299)

statusText - status code (ex: OK)

headers - Headers object associated with the response.

// 在service worker測試的時候
// 使用new Response(BODY, OPTIONS)創(chuàng)建一個response
var response = new Response(".....", {
    ok: false,
    status: 404,
    url: "/"
});

// The fetch的 `then`會獲得一個response實例
fetch("https://davidwalsh.name/")
    .then(function(responseObj) {
        console.log("status: ", responseObj.status);
    });

Response實例也提供了如下的方法:

clone() - Creates a clone of a Response object.

error() - Returns a new Response object associated with a network error.

redirect() - Creates a new response with a different URL.

arrayBuffer() - Returns a promise that resolves with an ArrayBuffer.

blob() - Returns a promise that resolves with a Blob.

formData() - Returns a promise that resolves with a FormData object.

json() - Returns a promise that resolves with a JSON object.

text() - Returns a promise that resolves with a USVString (text).

處理JSON

假設(shè)你有一個請求會返回JSON。

fetch("https://davidwalsh.name/demo/arsenal.json").then(function(response) { 
    // Convert to JSON
    return response.json();
}).then(function(j) {
    // Yay, `j` is a JavaScript object
    console.log(j); 
});

當(dāng)然也可以用JSON.parse(jsonString),但是json方法更加簡單易用。

處理基本的Text/HTML返回

不是所有的接口都返回JSON格式的數(shù)據(jù),所以還要處理一些Text/HTML類型的返回結(jié)果。

fetch("/next/page")
  .then(function(response) {
    return response.text();
  }).then(function(text) { 
      // 
處理Blob返回

如果你想要通過fetch加載一個blob的話,會有一點不同:

fetch("https://davidwalsh.name/flowers.jpg")
    .then(function(response) {
      return response.blob();
    })
    .then(function(imageBlob) {
      document.querySelector("img").src = URL.createObjectURL(imageBlob);
    });
POST Form數(shù)據(jù)

另一個經(jīng)常會遇到的情況是使用AJAX提交表單數(shù)據(jù)。

fetch("https://davidwalsh.name/submit", {
    method: "post",
    body: new FormData(document.getElementById("comment-form"))
});
最后

fetchAPI很好用,但是現(xiàn)在還不允許取消一個請求。無論如何,有了fetch之后,我們可以簡單的發(fā)出AJAX請求了。更多關(guān)于fetch 的內(nèi)容可以參考Github下他們的repo。

文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請注明本文地址:http://www.ezyhdfw.cn/yun/81213.html

相關(guān)文章

  • $.ajax vs axios vs fetch

    摘要:使用它可以讓頁面請求少量的數(shù)據(jù),而不用刷新整個頁面。這是一個比較粗糙的,不符合關(guān)注分離的設(shè)計原則,配置和使用都不是那么友好。它的一個優(yōu)勢異步操作,但的異步操作是基于事件的異步模型,沒有那么友好。 Ajax 是什么? 答:Ajax是一種可以在瀏覽器和服務(wù)器之間使用異步數(shù)據(jù)傳輸(HTTP請求)的技術(shù)。使用它可以讓頁面請求少量的數(shù)據(jù),而不用刷新整個頁面。而傳統(tǒng)的頁面(不使用Ajax)要刷新...

    bitkylin 評論0 收藏0
  • js基礎(chǔ)進階--從ajax到fetch的理解

    摘要:使用它可以讓頁面請求少量的數(shù)據(jù),而不用刷新整個頁面?;谑裁创鹚诘氖?。的庫答基于上面的原因,各種庫引用而生,然而最有名的就是的中的。它的一個優(yōu)勢異步操作,但的異步操作是基于事件的異步模型,沒有那么友好。 歡迎訪問我的個人博客:http://www.xiaolongwu.cn 基本知識 1. Ajax是什么? 答:Ajax是一種可以在瀏覽器和服務(wù)器之間使用異步數(shù)據(jù)傳輸(HTTP請求)...

    SoapEye 評論0 收藏0
  • ES6 Fetch API HTTP請求實用指南

    摘要:例子張三刪除用戶為了刪除用戶,我們首先需要定位用戶,然后我們定義方法類型。例子張三結(jié)論現(xiàn)在,你已基本了解如何使用的從服務(wù)器檢索或操作資源,以及如何處理。您可以使用本文作為如何構(gòu)建操作的請求的指南。 showImg(https://segmentfault.com/img/bVbjxqh?w=1000&h=562); 本次將介紹如何使用Fetch API(ES6 +)對REST API的...

    Sunxb 評論0 收藏0
  • fetch 如何請求數(shù)據(jù)

    摘要:四請求常見數(shù)據(jù)格式接下來將介紹如何使用請求本地文本數(shù)據(jù),請求本地數(shù)據(jù)以及請求網(wǎng)絡(luò)接口。請求網(wǎng)絡(luò)接口獲取中的數(shù)據(jù),做法與獲取本地的方法類似得到數(shù)據(jù)后,同樣要經(jīng)過處理 一 序言 在 傳統(tǒng)Ajax 時代,進行 API 等網(wǎng)絡(luò)請求都是通過XMLHttpRequest或者封裝后的框架進行網(wǎng)絡(luò)請求,然而配置和調(diào)用方式非?;靵y,對于剛?cè)腴T的新手并不友好。今天我們介紹的Fetch提供了一個更好的替代方...

    MarvinZhang 評論0 收藏0
  • fetch 如何請求數(shù)據(jù)

    摘要:四請求常見數(shù)據(jù)格式接下來將介紹如何使用請求本地文本數(shù)據(jù),請求本地數(shù)據(jù)以及請求網(wǎng)絡(luò)接口。請求網(wǎng)絡(luò)接口獲取中的數(shù)據(jù),做法與獲取本地的方法類似得到數(shù)據(jù)后,同樣要經(jīng)過處理 一 序言 在 傳統(tǒng)Ajax 時代,進行 API 等網(wǎng)絡(luò)請求都是通過XMLHttpRequest或者封裝后的框架進行網(wǎng)絡(luò)請求,然而配置和調(diào)用方式非?;靵y,對于剛?cè)腴T的新手并不友好。今天我們介紹的Fetch提供了一個更好的替代方...

    Betta 評論0 收藏0

發(fā)表評論

0條評論

最新活動
閱讀需要支付1元查看
<