0%

722_ajax_get请求

1-get.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #box {
        width: 200px;
        height: 100px;
        border: solid 1px pink;
      }
    </style>
  </head>
  <body>
    <button>点击发送请求</button>
    <div id="box"></div>
    <script>
      const btn = document.getElementsByTagName("button")[0];
      const box = document.querySelector("#box");
      btn.onclick = function () {
        //1、创建对象
        const xhr = new XMLHttpRequest();
        //2、初始化
        xhr.open("GET", "http://127.0.0.1:8000/server");
        //3、发送
        xhr.send();
        //4、事件绑定,处理服务端返回的结果
        xhr.onreadystatechange = function () {
          //判断(服务端返回了所有结果)
          if (xhr.readyState === 4) {
            //判断响应状态码 2##表示成功
            if (xhr.status >= 200 && xhr.status < 300) {
              //处理结果
              console.log(this);
              //1、响应行
              console.log(xhr.status); //状态码
              console.log(xhr.statusText); //状态字符串
              console.log(xhr.getAllResponseHeaders); //所有的响应头
              console.log(xhr.response); //响应体

              box.innerHTML = xhr.response;
            } else {
            }
          }
        };
      };
    </script>
  </body>
</html>

server.js

const express = require("express");

const app = express();

app.get("/server", (req, res) => {
  //设置运行跨域
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.send("Hello express2");
});

app.post("/server", (req, res) => {
  //设置运行跨域
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.send("Hello express post");
});

app.all("/json-server", (req, res) => {
  //设置运行跨域
  res.setHeader("Access-Control-Allow-Origin", "*");
  //响应一个数据
  const data = {
    name: "lzk",
  };
  //对对象进行字符串转换
  let str = JSON.stringify(data);
  res.send(str);
});

app.listen("8000", () => {
  console.log("8000端口监听中");
});