Fetch(簡易json傳輸)
fetch()的語法結構完全是Promise的語法
fetch('http://abc.com/', {method: 'get'})
.then(function(response) {
//處理 response
}).catch(function(err) {
// Error :(
})
fetch在伺服器有回應的情況下,都會回傳已實現的Promise物件狀態。所以在使用時還需要加一下檢查。(回傳404也算是實現,不算reject)
//有回應時要執行的函數
function processStatus(response) {
// 狀態 "0" 是處理本地檔案 (例如Cordova/Phonegap等等)
if (response.status === 200 || response.status === 0) {
return Promise.resolve(response)
} else {
return Promise.reject(new Error(response.statusText))
}
}
fetch(request)
.then(processStatus)
.then()
.catch()
Request(要求)
request直接傳入屬性
fetch('./sample.json', {
method: 'GET',
mode: 'cors',
redirect: 'follow',
headers: new Headers({
'Content-Type': 'text/json'
})
}).then(function(response) {
//處理 response
})
Request(要求)物件也可以直接作為fetch方法的傳入參數
const req = new Request(URL, {method: 'GET', cache: 'reload'})
fetch(req).then(function(response) {
//處理 response
}).catch(function(err) {
// Error :(
})
以下摘要Request(要求)物件中包含的屬性值:
method: GET, POST, PUT, DELETE, HEAD。
url: 要求的網址。
headers: 與要求相關的Headers物件。
referrer - no-referrer, client或一個網址。預設為client。
mode - cors, no-cors, same-origin, navigate。預設為cors。Chrome(v47~)目前的預設值是same-origin。
credentials - omit, same-origin, include。預設為omit。Chrome(v47~)目前的預設值是include。
redirect - follow, error, manual。Chrome(v47~)目前的預設值是。manual。
integrity - Subresource Integrity(子資源完整性, SRI)的值
cache - default, no-store, reload, no-cache, 或 force-cache
body: 要加到要求中的內容。注意,method為GET或HEAD時不使用這個值。
Response(回應)
純文字/HTML格式文字
//二個then傳入的function不同
fetch('/next/page')
.then(function(response) {
return response.text()
}).then(function(text) {
console.log(text)
}).catch(function(err) {
// Error :(
})
json格式
fetch('https://davidwalsh.name/demo/arsenal.json').then(function(response) {
// 直接轉成JSON格式
return response.json()
}).then(function(j) {
// `j`會是一個JavaScript物件
console.log(j)
}).catch(function(err) {
// Error :(
})
blob(原始資料raw data)
fetch('https://davidwalsh.name/flowers.jpg')
.then(function(response) {
return response.blob();
})
.then(function(imageBlob) {
document.querySelector('img').src = URL.createObjectURL(imageBlob);
})
FormData
FormData是在要求時傳送表單資料時使用。以下為範例:
fetch('https://davidwalsh.name/submit', {
method: 'post',
body: new FormData(document.getElementById('comment-form'))
})
Response(回應)物件中包含的屬性摘要如下:
type: basic, cors
url: 回應網址
useFinalURL: 布林值,代表這個網址是否為最後的網址(也可能是重新導向的網址)
status: 狀態碼 (例如: 200, 404, 500...)
ok: 代表成功的狀態碼 (狀態碼介於200-299)
status Text: 狀態碼的文字 (例如: OK)
headers: 與回應相關的Headers物件
Last updated
Was this helpful?