JS--原生Ajax

GET 请求

// GET 请求
// 创建XMLHTTPRequest对象
const xhr = new XMLHttpRequest();

// 设置请求的url参数,参数一是请求的类型,参数二是请求的url,可以带参数
xhr.open("get", `url地址?id=${id}`);

// 发送请求
xhr.send();

// 注册事件 onreadystatechange 状态改变就会调用
xhr.onreadystatechange = function () {

  if (xhr.readyState === 4 && xhr.status === 200) {

    console.log(xhr.response);
  }
}

POST 请求

// POST 请求
const xhr = new XMLHttpRequest();

// 配置请求头,post请求一定要添加请求头,不然会报错
xhr.setRequestHeader("Content-type","application/x-www-urlencoded");

xhr.open("POSt","url地址");
xhr.send(`id=${id}&age=${age}`);
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 200) {
    console.log(xhr.response);
  }
}
posted @ 2021-10-01 13:02  青柠i  阅读(28)  评论(0编辑  收藏  举报