Loading...
與上例的差異,只在於代入第二個參數:
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 的部份。