獲取資源很簡單,發起一個請求出去,一個響應進來,然后該怎么操作就怎么操作。
fetch 的 api 使用的是 promise 規范,不會 promise(用于延遲(deferred) 計算和異步(asynchronous ) 計算。 一個 Promise 對象代表著一個還未完成,但預期將來會完成的操作。主要使用它處理回調黑洞。) 的請花幾分鐘學習一下。
使用 fetch 去獲取數據的方式:
fetch("服務器地址")  .then(function(response) {    //將獲取到的數據使用 json 轉換對象    return response.json();  })  .then(function(data) {    //獲取轉換后的格式    console.log(data);  })  //如果有異常會在 catch 捕獲  .catch(function(e) {    console.log("error");  }); 有沒有發現使用 fetch 后代碼變優美了,不關心數據怎么請求的,把更多的精力放在處理數據上。
不用寫回調函數了,也不用監聽 xhr readystatechange 事件了,當數據請求回來后會傳遞給 then, 有異常就會直接觸發 catch 事件。
fetch 默認發起的是 get 請求,如果需要 post 請求需要設置 Request
Request
Request 客戶端向服務器發出請求的一個對象,包括用戶提交的信息以及客戶端的一些信息
使用 Request 構造一個 fetch 請求的對象的詳細信息
//實例化 request 對象var myRequest = new Request(url, Option);fetch(myRequest)  .then(function(response) {    console.log(response);  })  //如果有異常會在 catch 捕獲  .catch(function(e) {    console.log("error");  }); Request 詳細參數配置:
method
設置請求方式
method = GET / POST / PUT / DELETE / HEAD
headers
設置請求頭信息,使用 Headers 對象
let headers = new Headers({  'Content-Type': 'text/plain'}); mode
請求的模式,主要用于跨域設置
mode = cors / no-cors / same-origin
cors : 跨域
no-cors : 不跨域
same-origin : 同源
credentials
需要向服務器發送 cookie 時設置
credentials = omit / same-origin
omit : 省略
same-origin : 發送同源 cookie
cache
cache = default / reload / no-cache
redirect
收到重定向消息時如何處理
redirect = follow / error / manual
follow : 跟隨重定向的地址 ,繼續請求
error : 不請求
比如:
var request = new Request("url", {    headers: new Headers({      "Content-Type": "text/plain"    }),    method : "POST",    mode: "cors",    redirect : "follow"  });fetch(request)  .then((response) => {    console.log(response);  })  .catch((error)=>{    console.log(error);  }); fetch 數據處理
當 fetch 把請求結果拿到后,我們需要使用它提供的幾個方法來做處理
json
fetch 提供了一個 json 方法將數據轉換為 json 格式
fetch(url)  .then((response) => {    //返回 object 類型    return response.json();  })  .then((result) => {    console.log(result);  }); text
fetch 提供了一個 text 方法用于獲取數據,返回的是 string 格式數據
fetch(url)  .then((response) => {    //返回 string 類型    return response.text();  })  .then((result) => {    console.log(result);  });   blob
如果我們獲取的是一個圖像,需要先設置頭信息,然后 fetch 會正常處理本次請求,最終使用 blob 方法獲取本次請求的結果, 可以把結果賦值給 img src 就能正常的顯示一張圖片
var request = new Request("xx.img", {    headers: new Headers({      "Content-Type": "image/jpeg"    }),    method : "get",    cache: 'default'  });fetch(request)  .then((response) => {    return response.blob();  })  .then((stories)=>{    var objectURL = URL.createObjectURL(stories);    let img = document.createElement("img");    img.src = objectURL;    document.querySelector("body").appendChild(img);  }); 以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。
新聞熱點
疑難解答