原生 AJAX 具体用法

GET 请求
• 通常在一次 GET 请求过程中,参数传递都是通过 URL 地址中的 `?` 参数传递。
• 一般在 GET 请求中,无需设置请求头
• 无需设置响应体,可以传 null 或者干脆不传POST 请求
• POST 请求过程中,都是采用请求体承载需要提交的数据。
• 需要设置请求头中的 Content-Type,以便于服务端接收数据
• 需要提交到服务端的数据可以通过 send 方法的参数传递
  var xhr = new XMLHttpRequest();
    // 发送 GET 请求
    xhr.open("GET", "http://localhost:3000/users?age=19");
    xhr.send(null);
    xhr.onreadystatechange = function () {
      if (this.readyState === 4) {
        console.log(this.responseText);
      }
    }
 var xhr = new XMLHttpRequest();
    // post 请求
    xhr.open("POST","http://localhost:3000/users");
    // 设置请求头
    // xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    xhr.setRequestHeader("Content-Type","application/json");
    // xhr.send("name=lily&age=19&class=2");
    // xhr.send(`{
    //   "name": "lulu",
    //   "age": 18,
    //   "class": 2
    // }`);
    xhr.send(JSON.stringify({
      "name": "harry",
      "age": 18,
      "class": 1
    }));
    xhr.onreadystatechange = function () {
      if (this.readyState === 4) {
        console.log(this.responseText);
      }
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值