3.1 傳送一般資料

API: 簡易回傳資料

GET https://notes.webmix.cc/ajax/teach/simple_ajax.php

Query Parameters

NameTypeDescription

book_pages

string

頁數

book_published

string

書本發行日

基本會回傳前三個資料,若有提供book_published或book_pages的話,也會一併回傳。

{
  book_author: "某某作者",
  book_name: "某某書本",
  book_price: 399,
  book_published: "20200102",
  book_pages: "200"
}

建立 ajax/practice/xmlhttprequest.html 檔案,內容如下:

<!DOCTYPE html>
<html lang="zh-Hant">
  <head>
    <meta charset="utf-8">
    <title>XMLHTTPRequest</title>
  </head>
  <body>
    <h1>XMLHTTPRequest</h1>

    <script>
      // 1. 建立 XMLHttpRequest 物件
      let xhr = new XMLHttpRequest();

      // 2. 設定要向哪個網址取得資料,HTTP verb 為 GET,最後一個參數決定是否以非同步方式來執行
      xhr.open("GET", "https://notes.webmix.cc/ajax/teach/simple_ajax.php", true);
      //xhr.open("GET", "https://notes.webmix.cc/ajax/teach/simple_500.php", true);
      //xhr.open("GET", "http://127.0.0.1:5500/ajax/no_file.html", true);
      //xhr.open("GET", "https://notes.webmix.cc/ajax/teach/simple_no.php", true);

      // 3. 如果伺服器有回應的話,就會執行此函式
      xhr.addEventListener("load", function(){
        console.log("執行到 load 程式");
        console.log(xhr);
      });

      // 4. 如果產生錯誤,有可能執行這裡的程式
      xhr.addEventListener("error", function(){
        console.log("執行到 error 程式");
        console.log(xhr);
      });

      // 5. 無論是 load 或 error 觸發,最後 loadend 都會觸發
      xhr.addEventListener("loadend", function(){
        console.log("執行到 loadend 程式");
      });

      // 6. 發送請求
      xhr.send();

      //console.log("ajax 發送之後的程式");
    </script>
  </body>
</html>

練習:請將 xhr.response 轉成物件,在 console.log 中印出來。

Last updated