原生JS实现JQuery的$.ajax()方法

记录一下,方便以后ctrl+c v大法

COPY
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
/**
* 封装ajax请求
* @param {*} obj 请求参数
*/
function ajax(obj) {
//指定请求方式 默认get请求
obj.type = obj.type || "get";
//设置是否异步,默认为true
obj.async = obj.async || true;
//设置数据的默认值
obj.data = obj.data || null;

if (window.XMLHttpRequest) var ajax = new XMLHttpRequest();//非ie
else var ajax = new ActiveXObject("Microsoft.XMLHTTP");//ie

//将对象转为url参数
if (obj.data) {
var data = ""
Object.keys(obj.data).forEach(function (key) {
data += "&" + key + "=" + obj.data[key]
});
data = data.substring(1)
}

//区分get和post
if (obj.type == "post") {
ajax.open(obj.type, obj.url, obj.async);
ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
ajax.send(data);
} else {
var url = ""
if (obj.data) url = obj.url + "?" + data
else url = obj.url
ajax.open(obj.type, url, obj.async);
ajax.send();
}

ajax.onreadystatechange = function () {
if (ajax.readyState == 4) {
if (ajax.status >= 200 && ajax.status < 300 || ajax.status == 304) {
if (obj.success) { // 请求成功
obj.success(ajax.responseText);
}
} else {
if (obj.error) { // 请求失败
obj.error(ajax.status);
}
}
}
}
}
Authorship: Lete乐特
Article Link: https://blog.imlete.cn/article/JavaScript-Ajax.html
Copyright: All posts on this blog are licensed under the CC BY-NC-SA 4.0 license unless otherwise stated. Please cite Lete乐特 's Blog !