【03】AJAX发送get请求

一、发送GET请求

1.创建html文件:

test.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>
  </head>
  <body>
    <button id="btn">点击发送请求</button>
    <div id="dd"></div>
    <script>
      let btn = document.getElementById("btn");
      let dd = document.getElementById("dd");
      //为按钮btn绑定单击事件
      btn.onclick = function () {
        // 1.创建对象
        const xhr = new XMLHttpRequest(); //const设置常量
        // 2.初始化,设置请求方法'get'和url'http://127.0.0.1:8000'
        xhr.open("GET", "http://127.0.0.1:8000");
        // 3.发送
        xhr.send();
        // 4.事件绑定,处理服务端返回的结果
        /*onreadystatechange注解:
        on:当……时候
        readystate:是xhr对象中的属性,表示状态0 1 2 3 4
                0.未初始化
                1.open方法调用完毕    
                2.send方法调用完毕
                3.服务端返回部分结果
                4.服务端返回的所有结果
        change:改变*/
        xhr.onreadystatechange = function () {
          // 判断(服务器返回的所有结果)
          if (xhr.readyState === 4) {
            // 判断响应状态码:200 401 403 500
            // 2xx 表示成功,所以status的范围是[200,300)
            if (xhr.status >= 200 && xhr.status < 300) {
              console.log(xhr.status); //状态码
              console.log(xhr.statusText); //状态字符串
              console.log(xhr.getAllResponseHeaders()); //响应头
              console.log(xhr.response); //响应体

              dd.innerHTML = xhr.response; //将响应体中的内容添加到文本框dd中
            }
          }
        };
      };
    </script>
  </body>
</html>

test.js中的内容:

const express = require("express");
const app = express();
app.get("/", (request, response) => {
  response.setHeader("Access-Control-Allow-Origin", "*");
  response.send("HELLO EXPRESS");
});
app.listen(8000, () => {
  console.log("服务启动,800端口监听中……");
});

2.查看浏览器的显示结果:

二、设置请求参数

1.test.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>
  </head>
  <body>
    <button id="btn">点击发送请求</button>
    <div id="dd"></div>
    <script>
      let btn = document.getElementById("btn");
      let dd = document.getElementById("dd");
      btn.onclick = function () {
        const xhr = new XMLHttpRequest(); 
        // 设置请求参数a,b,c
        xhr.open("GET", "http://127.0.0.1:8000?a=100&b=200&c=300");
        xhr.send();
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4) {
            if (xhr.status >= 200 && xhr.status < 300) {
              dd.innerHTML = xhr.response; //将响应体中的内容添加到文本框dd中
            }
          }
        };
      };
    </script>
  </body>
</html>

test.js中的内容和上面相同。

2.查看浏览器的显示结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值