初步了解XMLHttpRequest对象、http请求的封装

 构造器

  var xhr = new XMLHttpRequest()

设置超时时间

 xhr.ontimeout=1000 设置超时时间为 1s

设置超时时间(单位:ms)

0为永不超时

HTTP 请求的状态

 xhr.readystate  从请求开始到完全结束,有5个状态分别对应不同的阶段,具体如下表:

当前阶段 状态码
new XMLHttpRequest() 0
xhr.open() 1
请求发出,未收到响应头 2
响应头接收ok,开始接收响应体 3
响应体接收完成 4

 

 

 

 

 

 

 

 

 

 

 

HTTP状态码

 xhr.status HTTP状态码

1xx  信息
2xx  成功

200:请求成功

3xx  重定向

304:重定向到:使用缓存

4xx  客户端错误

404:客户端错误

5xx  服务器错误

500:服务器遇到未知错误

状态码描述

 xhr.statusText 返回值状态码描述

默认值:''
默认编码:Unicode UTF-8

xhr.status === 200时,xhr.statusText === 'ok'

xhr.responseText:     请响应体body

 

xhr.responseXML

 xhr.responseXML 对请求的响应,解析为 XML 并作为 Document 对象返回。

 

 

 

 

对象的方法

 

 

 

方法                                           解释
xhr.abord() 关闭这个请求,将readyState重置为0
xhr.open() 打开一个HTTP请求
xhr.send() 发送HTTP请求
xhr.setRequestHeader() 向一个打开但未发送的请求设置或添加一个http请求头部
xhr.getAllResponseHeaders() 将HTTP响应头作为未解析的字符串返回
xhr.getResponseHeder() 返回指定的HTTP响应头部的值

 

 

 

 

 

 

 

 

 

 

 

 

 

 

对象的事件

onreadystatechange

当readyState改变时,触发的事件。

ontimeout

  请求超时

onloadend

  请求结束

onerror

  请求出错

One Example

let xml = new XMLHttpRequest();
xml.timeout = 0;  //设置超时时间:0永不超时
/**
 * xml.open(method, url, async, username?, password?)  
 *    打开一个请求,但不发送
 *    会重置readyState = 1、responseText、responseXML、status 以及 statusTex恢复默认值
 *    删除之前指定的所有的请求头部和响应头部
 */
xml.open('get', 'http://localhost:3000/api1')

/**
 * xml.send(body?: string)
 *    请求体
 *    post|put:string
 *    其他:null,或者不传
 * 
 *    发送open()时指定的mehods、URL、认证资格
 *    指定的setRequestHeader()
 *    传递body参数
 * 
 *    请求发出,send()将readyState设置为2,并处触发onreadystatechange
 */
xml.onprogress = function () {
  console.log( 111 )
}
xml.send()
xml.onloadend = function () {
  console.log( 'loadend...' )
}
xml.onerror = function () {
  console.log( 'onerror...' )
}
xml.onreadystatechange = function () {
  console.log( xml, xml.responseText )
  if(xml.readyState === 4){
    if(xml.status === 200){
      console.log( xml.responseText )
    }
  }
}

封装http请求函数

/**[接口域名] */
 const BASE_URL = 'http://localhost:3000'

 export default http = {
   /**
    * [query方法传参]
    */
   get (route, params) {
     return this.request('GET', this.getUrl(route, params))
   },
   /**
    * [body方法传参]
    */
   post (route, params) {
     return this.request('POST', this.getUrl(route), JSON.stringify(params))
   },
   /**
    * [body方法传参]
    */
   put (route, params) {
     return this.request('PUT', this.getUrl(route), JSON.stringify(params))
   },
   /**
    * [query方法传参]
    */
   delete (route, params) {
     return this.request('DELETE', this.getUrl(route, params))
   },
   /**
    * [body方法传参]
    */
   patch (route, params) {
     return this.request('PATCH', this.getUrl(route), JSON.stringify(params))
   },
   request (method, url, params) {
     return new Promise ((resolve, reject) => {
       params = typeof params === 'undefined' ? null : params
       const xhr = new XMLHttpRequest();
       xhr.open(method, url);
       xhr.send(params);
       xhr.onreadystatechange = function () {
         if( xhr.readyState === 4 ) {
           if( xhr.status === 200 ){
             resolve(JSON.parse(xhr.responseText))
           } else {
             new Error('请求失败,错误码为:' + xhr.status + '; 错误状态:' + xhr.statusText)
           }
         } else {
           new Error('请求失败')
         }
       }
     })
   },
   /**
    * [获取URL]
    */
   getUrl (route, params) {
     const reg = /^http|https/
     let url = ''
 
     if(!reg.test(route)){
       url = BASE_URL + route
     } else {
       url = route
     }
 
     return typeof params !== 'undefined' ? this.stringifyUrl(url, params) : url
   },
   /**[拼接参数] */
   stringifyUrl (url, params) {
     let paramsStr = ''
 
     Object.keys(params).forEach((key, i, arr) => {
       if(i < arr.length-1){
         paramsStr += key + '=' + params[key] + '&'
       } else {
         paramsStr += key + '=' + params[key]
       }
     })
 
     if(url.indexOf('?') > -1){
       url += '&' + paramsStr
     } else {
       url += '?' + paramsStr
     }
 
     return url
   }
 }
posted @ 2019-02-26 22:49  DaivdAndLemon  阅读(548)  评论(0编辑  收藏  举报