AJAX——POST請求


  • POST.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Ajax POST 請求測試</title>
  <style>
    #result {
      width: 200px;
      height: 100px;
      border: solid 1px rgb(15, 12, 15);
    }
  </style>
</head>
<body>
  <div id="result"></div>
  <script>
    //獲取元素對象
    const result = document.getElementById('result');
    //綁定事件
    result.addEventListener("mouseover",function(){     //事件監聽器
      // 1. 創建對象 
      const xhr = new XMLHttpRequest();
      // 2. 初始化 設置請求方法和url
      xhr.open('POST', 'http://127.0.0.1:8000/server')
      // 3. 發送
      xhr.send();
      // 4. 事件綁定 處理服務端返回的結果
      xhr.onreadystatechange = function(){
        // readyState 是 xhr 對象中的屬性, 表示狀態 0 1 2 3 4
        //判斷 (服務端返回了所有的結果)
        if(xhr.readyState === 4){
          //判斷響應狀態碼 200  404  403 401 500
          if(xhr.status >= 200 && xhr.status < 300){
            // 處理結果 行 頭 空行 體
            // 響應
            console.log('狀態碼', xhr.status); // 狀態碼
            console.log('狀態字符串', xhr.statusText); // 狀態字符串
            console.log('所有響應頭', xhr.getAllResponseHeaders()); // 所有響應頭
            console.log('響應體', xhr.response); // 響應體
            
            //設置 result 的文本
            result.innerHTML=xhr.response;
          }else{
          }
        }
      } 
    })
  </script>
</body>
</html>
  • server.js
// 1. 引入express
const express = require('express');

// 2. 創建應用對象
const app = express();

// 3. 創建路由規則
//Post請求
app.post('/server', (request, response) => {
  // 設置響應頭 設置允許跨域
  response.setHeader('Access-Control-Allow-Origin', '*');
  // 設置響應體
  response.send("Ajax_POST測試......");
});
// 4. 監聽服務
app.listen(8000, () => {
  console.log("服務已經啟動, 8000 端口監聽中...");
 })

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM