简单实现一个ajax

ajax

什么是Ajax

ajax:前后端分离后,都是后台通过接口返回数据,前端需要通过接口访问数据。那么这个通过接口访问后台数据的过程就叫ajax。

简单来说就是用 JS 向服务端发起一个请求,并获取服务器返回的内容

参考 :https://zhuanlan.zhihu.com/p/22564745

ajax 步骤

  1. 买手机 –> 创建ajax对象
  2. 拨号 –> 链接url接口地址 设置传输数据方法:get和post
    • get和post的区别:一般get获取数据,而post发送数据
      • get发送数据最多为2kb,post理论上没有限制,但不同浏览器有不同限制
      • get发送数据在url地址 post在消息内发送数据
      • get有缓存,相对不安全;post没有,相对安全
      • get方式和post方式传递的数据在服务端获取也不相同
  3. 说 –> 发送数据参数
  4. 听 –> 接收返回的数据,并渲染到html页面

简单实现

get

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var oAjax = new XMLHttpRequest();//创建ajax对象
oAjax.open('get','arr.txt');//链接地址 设置请求的方法
oAjax.send();//发送数据参数
oAjax.onreadystatechange = function(){//页面注册事件更新
if(oAjax.readyState == 4){//ajax执行状态码
if(oAjax.status == 200){//http状态码 200 说明一切ok
var data = oAjax.responseText;
// 异步获取数据 后续操作 都得写在这 可以封装函数传参 将data传出去
// console.log(typeof data);//string
// 将具有js格式的字符串 转换为js代码或数据

}
}
}

post

1
2
3
4
5
6
7
8
9
10
11
12
13
var oAjax = new XMLHttpRequest();
oAjax.open('post','aaa.txt');
oAjax.setRequestHeader('Content-type','application/x-www-form-urlencoded');//设置请求头传输数据的类型编码方式

oAjax.send();

oAjax.onreadystatechange = function(){//页面注册事件更新
if(oAjax.readyState == 4){//ajax执行状态码
if(oAjax.status == 200){//http状态码 200 说明一切ok
console.log(oAjax.responseText);
}
}
}

readyState ajax执行状态码

  • 0:初始化 还没有调用open()方法
  • 1: 载入 已调用send()方法,正在发送请求
  • 2: 载入完成 send()方法完成,已收到全部相应内容
  • 3: 解析 正在解析相应内容
  • 4: 完成 响应内容解析完成,可以在客户端使用了

status http状态码

  • 100-199 Infromationale responses 接受请求
  • 200-299 Successful responses 成功响应
  • 300-399 Redirects 重定向
  • 400-499 Client errors 客户端错误
  • 500-599 Sever errors 服务端错误

封装

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
   //封装一个ajax请求
function ajax(options){
//创建XMLHttpRequest对象
var request = window.XMLHttpRequest ? new XMLHttpRequest : new ActiveXObject()

//初始化参数的内容
options = options ||{}
options.type = (options.type ||'GET').toUpperCase()
options.dataType = options.dataType || 'json'
var params = options.data

//发送请求
if(options.type == 'GET'){
request.open('GET',options.url + '?' + params,true)
request.send(null)
}else if(options.type == 'POST'){
request.open('POST',options.url,true)
request.setRequestHeader('Content-Type', "application/x-www-form-urlencoded")//规定输出为键值对的形式
request.send(params)
}

//接收请求
request.onreadystatechange = function(){
if(request.readyState == 4){
var status = request.status
if (status >= 200 && status < 300){
options.success && options.success(request.responseText,request.responseXML)
}else{
options.fail &&options.fail(status)
}
}
}
}

// 调用
ajax({
type: 'post',
dataType: 'json',
data: {},
url: 'xxx',
success: function(text,xml){//请求成功后的回调函数
console.log(text)
},
fail: function(status){////请求失败后的回调函数
console.log(status)
}
})