# 首先要明白什么是XMLHttpRequest对象

XMLHttpRequest 对象用于在后台与服务器交换数据。

XMLHttpRequest 对象是开发者的梦想,因为您能够:

  • 在不重新加载页面的情况下更新网页
  • 在页面已加载后从服务器请求数据
  • 在页面已加载后从服务器接收数据
  • 在后台向服务器发送数据

AJAX中有检查状态码的, xmlHttp.onreadystatechange=handleStateChange;

function handleStateChange(){
    if(xmlHttp.readyState==4){
    if(xmlHttp.status==200){
    parseResults(); //解析返回值
    }
  }
}
1
2
3
4
5
6
7

XMLHTTP 的 readyState 值含义:

  • 0-未初始化,即尚未调用 open。
  • 1-初始化,即尚未调用 send。
  • 2-发送数据,即已经调用 send。
  • 3-数据传送中。
  • 4-完成。
ajax({
    methods : 'POST',
    url : 'test.php',
    async: true,
    data: {
        name: 'wang',
        password: '12345'
    },
    success : function (res) {
        console.log(res);
    },
    error : function (error) {
        console.log(error);
    }
})


function ajax(opt) {
    opt = opt || {};
    opt.methods = opt.methods.toUpperCase() || 'POST';
    opt.url = opt.url || '';
    opt.async = opt.async || ture;
    opt.data =  opt.data || null;
    opt.success = opt.success || function () {};
    var xmlHttp = null;
    if(XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
    }else{
        xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
    }
    var params = [];
    for(var key in opt.data) {
        params.push(key + '=' + opt.data[key]);
    }
    var postData = params.join('&');
    if (opt.method.toUpperCase() === 'POST') {
        xmlHttp.open(opt.method, opt.url, opt.async);
        xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');
        xmlHttp.send(postData);
    }
    else if (opt.method.toUpperCase() === 'GET') {
        xmlHttp.open(opt.method, opt.url + '?' + postData, opt.async);
        xmlHttp.send(null);
    }

    xmlHttp.onreadystatechange = function () {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            opt.success(xmlHttp.responseText);
        }
    };
};

let getJSON = function (url) {
    let promise = new Promise((resolve,reject)=>{
        let client = new XMLHttpRequest();
        client.open('GET',url);
        client.onreadystatechange = handler;
        client.responseType = 'json';
        client.setRequestHeader("Accept","application/json");
        client.send();

        function handler() {
            if(this.status === 200) {
                resolve(this.response);
            }else{
                reject(new Error(this.statusText));
            }
        }
    });
    return promise;
};
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71

promise 操作ajax

let getJSON = function (url) {
    let promise = new Promise((resolve,reject)=>{
        let client = new XMLHttpRequest();
        client.open('GET',url);
        client.onreadystatechange = handler;
        client.responseType = 'json';
        client.setRequestHeader("Accept","application/json");
        client.send();

        function handler() {
            if(this.status === 200) {
                resolve(this.response);
            }else{
                reject(new Error(this.statusText));
            }
        }
    });
    return promise;
};

getJSON("/posts.json").then((res)=>{
    console.log('Contents: ' + res);
},function (error) {
    console.error('出错了', error);
})
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