如何使用HTTP GET或POST進行Ajax呼叫?


我們需要使用JavaScript和像jQuery、Axios或Fetch API這樣的AJAX庫來使用HTTP GET或POST進行AJAX呼叫。Ajax(非同步JavaScript和XML)透過非同步更新內容而無需重新載入整個頁面來建立快速動態的網頁。它使用JavaScript從伺服器傳送和接收資料,這些資料可以是XML、JSON或純文字的形式。本教程將教我們如何使用HTTP GET或POST進行Ajax呼叫。

Ajax有兩種常見的請求型別:GET和POST。

GET請求

GET請求用於從伺服器檢索資料。GET請求通常用於從API檢索資料,因為它們不會對伺服器進行任何更改,因此被認為是安全且冪等的。

語法

使用者可以按照以下語法使用javascript的“XMLHttpRequest”物件使用GET請求進行Ajax呼叫。

let xhr = new XMLHttpRequest();
xhr.open("GET", "URL", true);
xhr.send(); 

這將建立一個新的“XMLHttpRequest”物件並開啟對給定URL的GET請求。最後,使用xhr.send()方法將GET請求傳送到伺服器。

請注意,您必須提供要從中檢索資料的API URL。

示例

以下示例演示如何使用JavaScript向https://jsonplaceholder.typicode.com/posts API發出GET請求以檢索資料。程式碼使用XMLHttpRequest物件開啟GET請求並處理來自伺服器的響應。響應資料被解析為JSON物件,並且使用innerHTML屬性在頁面上顯示前3個帖子的標題。

JSONPlaceholder API是一個免費的開源API,用於測試和原型設計。您也可以使用任何其他API。

<html>
<body>
   <h2><i>GET</i> Method Example</h2>
   <h3>Top 3 Blog Posts:</h3>
   <div id = "posts"> </div>
   <script>
      let xhr = new XMLHttpRequest();
      xhr.open("GET", "https://jsonplaceholder.typicode.com/posts", true);
      xhr.onreadystatechange = function() {
         if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
            let data = JSON.parse(xhr.responseText);
            let output = "";
            for (let i = 0; i < 3; i++) {
               output += "<p>" + data[i].title + "</p>";
            }
            document.getElementById("posts").innerHTML = output;
         }
      };
      xhr.send();
   </script>
</body>
</html>

使用XMLHttpRequest物件的POST請求

XMLHttpRequest可用於發出POST請求,這與GET請求類似,但資料傳送到請求正文而不是URL。open方法用於將請求方法設定為“POST”和URL,send方法用於傳送資料,onreadystatechange事件用於處理來自伺服器的響應。還可以根據需要設定內容型別和其他標頭。

語法

使用者可以按照以下語法使用POST請求進行Ajax呼叫。

var xhr = new XMLHttpRequest(); 
xhr.open("POST", "URL", true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(JSON.stringify(postData)); 

示例

以下示例演示使用XMLHttpRequest物件的POST請求。我們建立了一個表單,其中包含兩個輸入欄位,用於輸入帖子標題和正文以及提交按鈕。單擊提交按鈕時,將呼叫sendPostRequest()函式,該函式向“https://jsonplaceholder.typicode.com/posts”端點發出POST請求。該函式設定請求標頭以指示內容型別為JSON,並以JSON格式傳送帖子資料。我們還會顯示成功狀態。

<html>
<body>
   <h2><i>POST</i> request example</h2>
   <input type = "text" id = "title" placeholder = "Enter post title">
   <br> <br>
   <textarea id = "body" placeholder = "Enter post body"></textarea><br>
   <br>
   <button onclick = "sendPostRequest()">Submit</button> <br> <br>
   <div id = "response" ></div>
   <script>
      function sendPostRequest() {
         var postData = {
            title: document.getElementById("title").value,
            body: document.getElementById("body").value
         };
         var xhr = new XMLHttpRequest();
         xhr.open("POST", "https://jsonplaceholder.typicode.com/posts", true);
         xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
         xhr.send(JSON.stringify(postData));
         xhr.onreadystatechange = function() {
            if (xhr.readyState === 4 && xhr.status === 201) {
               document.getElementById("response").innerHTML = "Post request successful: " + xhr.responseText;
            } else {
               document.getElementById("response").innerHTML = "Post request failed: " + xhr.responseText;
            }
         };
      }
   </script>
</body>
</html> 

使用Fetch的POST請求

fetch是一種用於進行網路請求的現代方法。它透過傳遞URL和一個選項物件作為引數來發出POST請求。選項物件將請求方法指定為“POST”,並將標頭“Content-Type”設定為“application/json”。請求資料作為字串化的JSON物件傳遞給選項物件的body屬性。然後使用.then()方法處理來自伺服器的響應,該方法返回來自響應的JSON資料。

示例

以下示例演示使用fetch的POST請求。一個簡單的表單向JSON佔位符API傳送POST請求。提交後,響應資料將使用HTML預標籤進行格式化顯示。

<html>
<body>
   <h2>Create New Blog Post:</h2>
   <form>
      <input type = "text" id = "title" placeholder = "Title" required>
      <textarea id = "body" placeholder = "Body" required> </textarea>
      <button type = "button" id = "submitBtn"> Submit </button>
   </form> <br>
   <h2>Response:</h2>
   <pre id = "response" ></pre>
   <script>
      document.getElementById("submitBtn").addEventListener("click", function() {
         let title = document.getElementById("title").value;
         let body = document.getElementById("body").value;
         let data = {
            title: title,
            body: body 
         };
         fetch("https://jsonplaceholder.typicode.com/posts", {
            method: "POST",
            headers: {
               "Content-Type": "application/json"
            },
            body: JSON.stringify(data)
         })
         .then(response => response.json())
         .then(data => {
            document.getElementById("response").innerHTML = JSON.stringify(
               data,
               null,
               2
            );
         });
      });
   </script>
</body>
</html>

我們已經學習瞭如何使用JavaScript的XMLHttpRequest物件以及使用fetch和不同的示例來使用HTTP GET或POST進行Ajax呼叫。

更新於:2023年2月22日

7K+ 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.