Fork me on GitHub

初步实现Axios

关于Axios

axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,它本身具有以下特征:

  • 从浏览器中创建 XMLHttpRequest
  • 从 node.js 发出 http 请求
  • 支持 Promise API
  • 拦截请求和响应
  • 转换请求和响应数据
  • 取消请求
  • 自动转换JSON数据
  • 客户端支持防止CSRF/XSRF

本次主要实现浏览器的XMLHttpRequest请求,使用原生方法,使用promise封装实现;

关于原生Ajax

初步认识ajax

1
2
3
4
5
6
7
8
var xhr = new XMLHttpRequest();
xhr.open('get', 'http://localhost:3002/login', true);
xhr.send();
xhr.onreadystatechange = function() {
console.log(xhr.readyState)
console.log(xhr.responseText)
console.log(xhr.status)
};

详细解析

构建对象

使用XMLHttpRequest构造函数构造ajax对象,注意此方法在IE有兼容行
兼容写法

1
2
3
4
5
6
7
var xhr = null;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
// xhr = new ActiveXObject('Microsoft.XMLHTTP');
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
参数

open方法参数:

  • type(post、get)
  • url:路径
  • async:是否异步:true、false
    如果是同步情况下,获得文本内容不用使用回调函数,直接xhr.responseText就可以
发送参数

send方法

  • get请求默认null;
  • post请求根据请求数据格式设置不同的请求头
1
json:xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
处理响应

处理相应方法为onreadystatechange回调函数

关于readyState:

  • 0:xhr对象初始化
  • 1:执行发送动作
  • 2:服务端数据已经完全返回
  • 3:数据正在解析
  • 4:数据解析完成,可以使用了

原生封装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
function myAjax(type, url, param, callback) {
//Ajax语法结构
var xhr = null;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
// xhr = new ActiveXObject('Microsoft.XMLHTTP');
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
if (type == 'get') {
url += '?' + encodeURI(param);
}
xhr.open(type, url);
var data = null;
if (type == 'post') {
//如果是post提交,需要将参数传给send;
data = param;
//设置请求头
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
xhr.send(data);
//处理响应
xhr.onreadystatechange = function() {
if (xhr.status == 200 && xhr.readyState == 4) {
var result = xhr.responseText;
result = JSON.parse(result)
callback(result);
}
};
}