4.2 傳送一般資料

請在 practice 資料夾下,建立 fetch.html,測試以下原始碼:

<!DOCTYPE html>
<html lang="zh-Hant">
  <head>
    <meta charset="utf-8">
    <title>Fetch</title>
  </head>
  <body>
    <h1>fetch 語法</h1>
    
    <script>
      // 1、GET API,資料的傳遞一定在網址上
      var fetch_url = "https://notes.webmix.cc/ajax/teach/simple_ajax.php?book_pages=123";
      
      fetch(fetch_url).then((res) => {
        if(res.ok){
          return res.json();
        }
      }).then((data) => {
        console.log(data);
      });
      
      

      // 2、示範 POST API,傳遞 JSON 格式字串化
      /*
      let car = {price: 100, color: "black"};
      // 此 API 僅僅只是將傳過來的 JSON 資料,再原封不動的直接回傳
      var fetch_url = "https://notes.webmix.cc/ajax/teach/simple_json.php";
      
      fetch(fetch_url, {
        method: "POST",
        body: JSON.stringify(car),
        headers: {
          "Content-Type": "application/json;charset=utf-8"
        }
      }).then(res => res.json()).then(data => {
        console.log(data);
      });
      */
      
      

      // 3、示範 PUT API,傳遞 FormData,但要經過 new URLSearchParams()
      /*
      let form_data = new FormData();
      form_data.append("price", 200);
      form_data.append("color", "red");
      
      // 此 API 僅僅只是將傳過來的 JSON 資料,再原封不動的直接回傳
      var fetch_url = "https://notes.webmix.cc/ajax/teach/simple_form_data_url_search_params.php";
      fetch(fetch_url, {
        method: "PUT",
        body: new URLSearchParams(form_data)
      }).then(res => res.json()).then(data => {
        console.log(data);
      });
      */
    </script>
  </body>
</html>

Last updated