Ajax请求:请求参数

<!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="requestGET">发送GET请求(query参数)</button>

    <button id="requestPOST">发送POST请求(body参数)</button>

    <button id="requestGET2">发送GET请求(params参数)</button>
  </body>
  <script>
    /* 
       请求参数:发起网络请求时向服务端发送的数据

       1、get请求 参数类型:query
         语法:在请求地址的末尾通过 ?拼接 参数名1=参数值1&参数名2=参数值2
    */

    requestGET.onclick = function () {
      const oajax = new XMLHttpRequest();

      oajax.open("GET", "http://localhost:3000/userlist?uid=10001", true);

      oajax.responseType = "json";

      oajax.send();

      //请求接口触发的回调函数
      oajax.onload = function () {
        console.log("获取http响应状态", oajax.status);
        console.log("获取http响应状态", oajax.statusText);
        console.log("获取响应结果", oajax.response);
      };
    };

    /* 
       请求参数:发起网络请求时向服务端发送的数据
       2、post请求 通过请求体方式  body
         语法: {
              参数名称:参数值
              参数名称:参数值
         }
    */

    requestPOST.onclick = function () {
      const oajax = new XMLHttpRequest();

      oajax.open("POST", "http://localhost:3000/userInfo", true);

      oajax.responseType = "json";

      //设置请求头  content-type 设置发送的数据数据 application/json 以json格式
      //  application/x-www-form-urlencoded 表单类型
      oajax.setRequestHeader("content-type", "application/json");

      //send方法的参数为请全体参数
      oajax.send(
        JSON.stringify({
          uid: 10001,
        })
      );

      //请求接口触发的回调函数
      oajax.onload = function () {
        console.log("获取http响应状态", oajax.status);
        console.log("获取http响应状态", oajax.statusText);
        console.log("获取响应结果", oajax.response);
      };
    };

    /* 
      请求参数:发起网络请求时向服务端发送的数据
       3 以路径参数的形式 params (路径参数)
         语法: 请求地址/参数值1/参数值2
    */

    requestGET2.onclick = function () {
      const oajax = new XMLHttpRequest();

      oajax.open("GET", "http://localhost:3000/bookdetail/98981", true);

      oajax.responseType = "json";

      //send方法的参数为请全体参数
      oajax.send();

      //请求接口触发的回调函数
      oajax.onload = function () {
        console.log("获取http响应状态", oajax.status);
        console.log("获取http响应状态", oajax.statusText);
        console.log("获取响应结果", oajax.response);
      };
    };
  </script>
</html>

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值