初步了解XMLHttpRequest对象、http请求的封装
构造器
var xhr = new XMLHttpRequest()
设置超时时间
xhr.ontimeout= 设置超时时间为 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 返回值状态码描述
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
}
}
初步了解XMLHttpRequest对象、http请求的封装的更多相关文章
- Ajax异步请求XMLHttpRequest对象Get请求
$(function () { $("#btnGetDate").click(function () { var xhr; //第一步:创建异步请求的核心的对象: if (XMLH ...
- Ajax技术---核心XMLHttpRequest对象
Ajax 的全称是Asynchronous JavaScript and XML,其中,Asynchronous 是异步的意思,它有别于传统web开发中采用的同步的方式. (一)ajax技术的意义 我 ...
- Ajax中的XMLHttpRequest对象详解
XMLHttpRequest对象是Ajax技术的核心.在Internet Explorer 5中,XMLHttpRequest对象以ActiveX对象引入,被称之为XMLHTTP,它是一种支持异步请求 ...
- javascript XMLHttpRequest对象全面剖析
转载:http://www.jb51.net/article/23175.htm 一. 引言 异步JavaScript与XML(AJAX)是一个专用术语,用于实现在客户端脚本与服务器之间的数据交互过程 ...
- 全面剖析XMLHttpRequest对象
XMLHttpRequest对象是当今所有AJAX和Web 2.0应用程序的技术基础.尽管软件经销商和开源社团现在都在提供各种AJAX框架以进一步简化XMLHttpRequest对象的使用:但是,我们 ...
- Ajax中的XMLHttpRequest对象详解(转)
XMLHttpRequest对象是Ajax技术的核心.在Internet Explorer 5中,XMLHttpRequest对象以ActiveX对象引入,被称之为XMLHTTP,它是一种支持异步请求 ...
- window.XMLHttpRequest对象详解
来自:http://blog.csdn.net/lccone/article/details/7743946 window.XMLHttpRequest XMLHttpRequest对象是当今所有AJ ...
- 轻松掌握XMLHttpRequest对象------【这是.net 版本】
轻松掌握XMLHttpRequest对象 XmlHttp是什么? 最通用的定义为:XmlHttp是一套可以在Javascript.VbScript.Jscript等脚本语言中通过http协议传送或从接 ...
- 轻松掌握XMLHttpRequest对象
XmlHttp是什么? 最通用的定义为:XmlHttp是一套可以在Javascript.VbScript.Jscript等脚本语言中通过http协议传送或从接收XML及其他数据的一套API.XmlHt ...
随机推荐
- jzyz集训 0611
今天jjh和mzx搞的互测题目有必要记录一下. T1:序列上可以放012三种颜色,有m个限制表示[l,r]区间的颜色数目必须是c,求方案数. 显然的DP,但关键是状态怎么设置,连续设置了n个状态都被自 ...
- python的模块导入问题
以下内容参考:http://www.xinxingjiaocheng.com/online/item/7/89 1.给模块起个别名 如果一个模块的名字很长很长,就像这样comput_the_value ...
- html5--2.4新的布局元素(3)-section
html5--2.4新的布局元素(3)-section 学习要点 了解section元素的语义和用法 通过实例理解section元素的用法 article元素和section元素的区别和共同点 art ...
- 分享知识-快乐自己:SpringMvc中 页面日期格式到后台的类型转换
日期格式的类型转换: 以往在 from 表单提交的时候,都会有字符串.数字.还有时间格式等信息. 往往如果是数字提交的话底层会自动帮我们把类型进行了隐式转换. 但是日期格式的却不能自动转换,这就需要我 ...
- ES 搜索结果expalain 可以类似数据库性能调优来看排序算法的选择
When we run a simple term query with explain set to true (see Understanding the Score), you will see ...
- 1053 Path of Equal Weight (30)(30 分)
Given a non-empty tree with root R, and with weight W~i~ assigned to each tree node T~i~. The weight ...
- 【LeetCode】259 3Sum Smaller
题目: Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 ...
- tyvj1659救援队——最小生成树
题目:http://www.joyoi.cn/problem/tyvj-1659 想清楚了是非常简单的最小生成树: 1.树中每条边都会被走两边: 2.每个点会走度数遍,起点又多走一遍: 根据以上两条处 ...
- C# 序列化反序列化XML的帮助类
以下是一个包装的用于序列化反序列化XML和C# 对象的类. public class XmlSerializeHelper<T> { #region Serial ...
- LTE协议
开启通信不归路的第一炮!----LTE整体框架和协议架构概述 (2015-03-09 09:07:04) 转载▼ 分类: 通信那些事儿 听说“态度.决心.毅力和细心”一定可以成就一个人!而我们也总 ...