XHR对象请求

270 阅读2分钟

1. 使用HXR发送GET请求

// 1.创建xhr对象
const xhr = new XMLHttpRequest();
// 2.调用open()方法
open(请求方式,请求地址)
   xhr.open('GET',"http://www.liulongbin.top:3006/api/getbooks")
// 3.调用send()
   xhr.send();        
// 4.设置事件监听        
xhr.onreadystatechange = function(){
            if(xhr.readyState==4&&xhr.status==200){
                console.log(JSON.parse(xhr.responseText));
            }
}

2. XMLHttpRequest对象的readyState属性用来表示当前ajax请求所处的状态,  每个ajax请求必然处于以下状态的一个

// XMLHttpRequest对象的readyState属性用来表示当前ajax请求所处的状态
// 每个ajax请求必然处于以下状态的一个
const xhr = new XMLHttpRequest();
console.log(xhr.readyState)  //0 UNSENT 表示对象已被创建,但是还没有调用open()方法
xhr.open("GET","http://www.liulongbin.top:3006/api/getbooks")
console.log(xhr.readyState)  //1  OPENED open()方法已调用
xhr.send()
console.log(xhr.readyState)  //1
xhr.onreadystatechange = function() {
     console.log(xhr.readyState) //2 3 4
     // 2 HEADER_RECEIVED  send()方法已调用,响应头已经被接收
     // 3 LOADING  数据接收中,此时response中已经有部分数据
     // 4 DONE ajax请求数据传输数据完成或失败
     //  请求状态         网络状态
     if(xhr.readyState==4&&xhr.status==200){
          console.log(xhr.responseText)
     }
}

3.1  使用xhr发起的带参数的get请求

使用xhr对象发起的带参数的GET请求时,只需在调用xhr.open()期间,  为url地址指定参数即可,这种url地址后面拼接的参数,叫做查询字符串

xhr.open("get","http://www.liulongbin.top:3006/api/getbooks?id=1")

(1)查询字符串:

  • 定义:查询字符串是指在url的末尾加上用于向服务器发送信息的字符串
  • 格式: url? 参数=值&参数=值&参数=值

无论时使用.ajax(),还是使用.ajax(),还是使用.get(),又或是直接使用xhr对象发起的GET请求,  当要携带参数的时候,本质上都是直接将参数已查询字符串的形式,追加到url地址的后面,发送到服务器

(2)url编码与解码: 

  •  encodeURI("程序员")       
  • decodeURI("%E5%91%98")

3.2 使用xhr发起的带参数的post请求

   // 无法对“XMLHttpRequest”执行“setRequestHeader”
   // Uncaught DOMException: Failed to execute 'setRequestHeader' on 'XMLHttpRequest':
   // The object's state must be OPENED.
   const xhr = new XMLHttpRequest();
   xhr.open('POST',"http://www.liulongbin.top:3006/api/addbook")
   //错误!!!!!!!! 设置请求头,写在open()方法之后,send()方法之前
   xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
   xhr.send("bookname=正方体&author=莱布尼茨&publisher=物理")
   console.log(xhr.readyState)       // 1
   // xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
   xhr.onreadystatechange = function(){
      if(xhr.readyState == 4 && xhr.status == 200){
         console.log(JSON.parse(xhr.response))
      }
   }