人生人山人海人来人往,自己自尊自爱|

青柠i

园龄:4年3个月粉丝:11关注:1

2021-10-01 13:02阅读: 31评论: 0推荐: 0

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 @   青柠i  阅读(31)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起