xhr get 发送请求和 xhr post发送请求

641 阅读1分钟

xhr get发送请求


  <script>
    // 1创建xmLhttrquerst实列对象
    let xhr=new XMLHttpRequest()
    // 设置请求方式和资源路径 axios设置查询参数 都是渲染到路径末尾
    xhr.open("GET",'http://www.liulongbin.top:3009/api/getbooks?id=1')
    // 3发送
    xhr.send()
    // 4接受
    xhr.onload=function(){
      // xhr.responese 接受到的响应信息(JSON类型的字符串)
      console.log(xhr.response)
      // axios返回六个属性,XHM返回的就是原始数据,未包装过
      console.log(JSON.parse(xhr.response))
    }
  </script>

xhr post发送请求

//1.创建xhr对象
       let xhr = new XMLHttpRequest()
       //2.设置请求方法和资源路径
       xhr.open('POST','http://www.liulongbin.top:3009/api/addbook')
       //3.1发送请求1
       //用请求头,标注参数类型
       xhr.setRequestHeader('content-type','application/x-www-form-urlencoded')
       //请求体参数,要写到send()里面
       xhr.send('bookname=三体订单&author=大刘订单&publisher=武汉人民出版订单社')
       //3.2发送请求2
       //xhr.setRequestHeater('content-type','application/json')
       //请求体参数,要写到send()里面
       //xhr.send('{"bookname":"三体二","author":"大刘","publisher":"人民出版社"}')
       //4.接收
       xhr.onload=function(){
         console.log(xhr.response)
       }