java script fetch 用法
阿新 • • 發佈:2019-02-18
基本的fetch
用法
fetch
方法是全域性物件window
裡提供的,它的第一個引數就是URL地址:
// url (required), options (optional) fetch('/some/url', { method: 'get' }).then(function(response) { }).catch(function(err) { // Error :( });
這個fetch API使用promises處理結果results/callbacks:
// Simple response handling fetch('/some/url').then(function(response) { }).catch(function(err) { // Error :( });; // Chaining for more "advanced" handling fetch('/some/url').then(function(response) { return //... }).then(function(returnedValue) { // ... }).catch(function(err) { // Error :( });;
如果你以前沒有用過then
類似的方法,那就學著使用它吧——很快到處都會出現這種方法。
處理JSON
假如說,你需求發起一個JSON請求 — 返回的資料物件裡有一個json
方法,能將原始資料轉化成JavaScript物件:
fetch('http://www.webhek.com/demo/arsenal.json').then(function(response) { // Convert to JSON return response.json(); }).then(function(j) { // Yay, `j` is a JavaScript object console.log(j); });
顯然,它就是一個簡單的JSON.parse(jsonString)
呼叫,但json
方法做為簡寫方式還是很方便的。
處理基本的Text/HTML響應
JSON並不是我們在任何時候都需要的資料格式,下面介紹一下如何處理HTML或文字格式的響應:
fetch('/next/page') .then(function(response) { return response.text(); }).then(function(text) { // <!DOCTYPE .... console.log(text); });
非常相似,你可以在Promise的then
text()
。
頭資訊和元資訊(Metadata)
response
物件裡還包含了豐富的HTTP頭資訊和metadata資訊,你可以直接用get
方法獲取它們:
fetch('http://www.webhek.com/demo/arsenal.json').then(function(response) { // Basic response properties, available at any time console.log(response.status) console.log(response.statusText) // Grabbing response headers via `get` console.log(response.headers.get('Content-Type')) console.log(response.headers.get('Date')) })
你還可以在呼叫請求過程中set這些頭資訊:
// url (required), options (optional) fetch('/some/url', { headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' } });
提交表單資訊
Ajax另外一個常用的地方是傳送表單資料,下面的這個例子就是如何用fetch
傳送表單資料:
fetch('/submit', { method: 'post', body: new FormData(document.getElementById('comment-form')) });
如果你傳送的資料是JSON格式:
fetch('/submit-json', { method: 'post', body: JSON.stringify({ email: document.getElementById('email') answer: document.getElementById('answer') }) });
非常容易,而且看起來也非常順眼!