fetch("request 的網址").then(function(response){ // 接收到回傳的物件
if(response.ok){ // 如果正確取得資料,沒有發生錯誤
return response.json(); // 將取得的資料,再使用 .json() 解析資料
}
}).then(function(data){ // 這裡真的取得資料:data
console.log(data);
}).catch(function(error){ // 發生任何錯誤,就會執行 catch 裡的程式
console.log(error); // 這裡取得錯誤資訊:error
})
fetch("request 的網址", {
method: "POST", // 以 POST 為例
body: 資料 // 欲傳送的資料
}).then // 這裡省略不寫,同上述 GET 的部份。
fetch 語法無法做「檔案上傳進度」的監聽。
建立 upload_file_fetch.html
,貼以下的原始碼,執行看看:
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="utf-8">
<title>使用 fetch 來將檔案上傳</title>
</head>
<body>
<h1>使用 fetch 語法</h1>
<input type="file" id="the_file" accept="image/*">
<div class="upload_status"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(function(){
$("#the_file").on("change", function(){
// here
//console.log(this.files);
let form_data = new FormData();
form_data.append('the_file', this.files[0]);
$("div.upload_status").html("檔案傳送中…");
// 使用 fetch 語法傳送檔案
fetch("https://notes.webmix.cc/html5_tutorial/file/file_receive.php", {
method: "POST",
body: form_data
}).then(response => response.json()).then((data) => {
console.log(data);
$("div.upload_status").html("檔案傳送完成");
}).catch((error) => {
console.log(error);
$("div.upload_status").html("檔案傳送失敗");
});
});
});
</script>
</body>
</html>
請在 practice
資料夾下,建立 fetch.html
,測試以下原始碼:
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="utf-8">
<title>Fetch</title>
</head>
<body>
<h1>fetch 語法:GET</h1>
<script>
var fetch_url = "https://notes.webmix.cc/ajax/teach/simple_ajax.php";
//var fetch_url = "https://notes.webmix.cc/ajax/teach/simple_500.php";
//var fetch_url = "http://127.0.0.1:5500/ajax/no_file.html";
//var fetch_url = "https://notes.webmix.cc/ajax/teach/simple_no.php";
fetch(fetch_url).then(function(res){ // 接收到回傳的物件
if(res.ok){ // 如果正確取得資料,沒有發生錯誤,會是 true
return res.json(); // 將取得的資料,再使用 .json() 解析資料
}
}).then(function(data){ // 這裡真的取得資料:data
console.log(data);
}).catch(function(err){ // 若發生錯誤,會執行 catch 裡的程式
console.log(err);
});
//console.log("非同步,故這裡會先印出來");
</script>
</body>
</html>
其它寫法(改成使用箭頭函式):
fetch(fetch_url).then(res => res.json()).then(data => {
console.log(data);
});