Fetch
會將400,500都當做請求成功,需另做處理
不支援timeout handle
不支援監測請求的進度
較早的瀏覽器不支援(IE11以下)
code:javascript
const result = document.querySelector(".result");
.then((response) => {
console.log(response);
return response.json();
})
.then((data) => {
var email = data.results0.email; result.textContent = email;
})
.catch((err) => {
console.log(err);
});
code:javascript
fetch('/foobar', {
method: 'POST',
body: 'foo=1&bar=2',
headers: new Headers({ 'Content-type': 'application/x-www-form-urlencoded' }),
})
.then( (response) => {
if (response.status === 200) {
console.log('Success');
} else {
console.log('Failed');
}
})
.catch( (err) => {
console.log('Error');
}
code:javascript
async function fileDownloadFromUrl(fileName, fileUrl) {
const response = await fetch(fileUrl);
const blob = await response.blob();
const newBlob = new Blob(blob); const objUrl = window.URL.createObjectURL(newBlob);
const link = document.createElement("a");
link.href = objUrl;
link.download = fileName;
link.click();
// For Firefox it is necessary to delay revoking the ObjectURL.
setTimeout(() => {
window.URL.revokeObjectURL(objUrl);
}, 250);
}