实现原生JS封装一个AJAS

前言:我们的使用ajax实现异步请求数据的时候,通常都是使用jQuery封装好的方法。

什么是AJAX?

​ A J A X = asynchronous javascript and xml

​ ajax可以将数据作为纯文本或者json文本传输。ajax允许通过与场景后面web服务器交换数据来异步更新网页,既不需要重新加载整个页面。

JQuery方法

简单快捷,是需要几步代码搞定

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$.ajax({
url: "data.json",
type: "GET",
dataType: "json",
data: {
mobile: 13500010101
},
success: function (data) {
temp = data;
return temp;
},
error: function (data) {
console.log('error', data);
}
})

但我们不用JQuery的时候要怎么使用原生js来封装呢?

原生JS方法

  1. 首先创建XMLHttpRequest对象

    现代浏览器都有内建的XMLHttpRequest对象,老旧浏览器(IE5 ,IE6)需要使用ActiveXObject对象

  2. GET请求

    1
    2
    xhttp.open("GET", "data.json", true);
    xhttp.send();
  3. POST请求

    1
    2
    3
    xhttp.open("POST", "ajax_test.asp", true);
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhttp.send("fname=Bill&lname=Gates");
  4. 最终实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function fn() {
var xhttp;
if(window.XMLHttpRequest){
xhttp = new XMLHttpRequest();
}else{
xhttp = new ActiveXObject("Microsoft.XMLHttp")''
}
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
data = JSON.parse(this.response);
}
}
xhttp.open("GET", "data.json", true);
xhttp.send();
}

​ 5. 这里补充一下,response里面存的是JSON类型的字符换,使用JSON.parse()方法可以使JSON字符串转换为js对象,这样调用起来就很方便了。

评论