Ajax原理及封装

Ajax原理及封装

封装Ajax请求函数。

原生js的Ajax请求

  1. 创建xhr实例
1
2
3
4
5
6
7
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
// IE6, IE5
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
  1. 调用open(), send()方法
1
2
xhr.open(method, url, async);
xhr.send(string); // 用于POST请求

实例:GET

1
2
3
4
5
xhr.open('GET', 'a/b/data.php', true);
xhr.send();

xhr.open('GET', 'a/b/data.php?num=' + Math.random(), true);
xhr.send();

实例:POST

1
2
3
4
5
6
7
xhr.open('POST', 'a/b/data.php', true);
xhr.send();

// 模拟form表单POST
xhr.open('POST', 'a/b/data.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); // 添加http请求头
xhr.send("fname=Henry&lname=Ford");
  1. 监听状态改变
1
2
3
4
5
6
7
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
xhr.open("GET", "a/b/data.php", true);
xhr.send();

如果 asyncfalse ,则不能写 onreadystatechange() ,这时Ajax已经是同步执行了,故而只需要先 open()send() ,最后使用 xhr.responseText 既可:

1
2
3
xhr.open("GET", "a/b/data.php", false);
xhr.send();
alert(xhr.responseText);
  1. 服务器响应

使用 responseText (字符串)和 responseXML (XML)来获取服务器响应数据。
如果服务器响应的数据为XML则使用 responseXML ,否则使用 responseText

对于 responseXML ,获取到了之后使用DOM方法操作。

  1. onreadystatechange事件

onreadystatechange 事件用于监听 readystate 的改变。

readyState属性值:

  • 0:请求未初始化
  • 1:服务器连接已建立
  • 2:请求已接收
  • 3:请求处理中
  • 4:请求已完成,响应已就绪

常用的status属性值:

  • 200:OK
  • 404:找不到页面

更多http状态码:http状态码

基于原生js封装Ajax

从上面可以看出,封装一个Ajax方法所需要的无非就是以下几点:

  • 入参:

    • url(string)
    • method(string)
    • async(boolean)
    • param(json)
    • success(function)
    • error(function)
    • complete(function)
  • 出参:

    • data(json)
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
ajax({
url: '/a/b/data.php',
method: 'GET',
param: {
name: 'Mason',
age: 22
},
async: true,
success: function(data) {

},
error: function(xhr) {

},
complete: function(xhr) {

}
});

/**
* 传入options参数对象
* @param options 参数对象
*/
function ajax(options) {
let xhr;

if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}

if (options.method === 'GET') {
xhr.open(options.method, options.url + '?' + parseParam(options.param), options.async);
xhr.send();
} else if (options.method === 'POST') {
xhr.open(options.method, options.url, options.async);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(options.param);
}

xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
options.success(xhr.responseText);
} else if (xhr.readyState === 4 && xhr.status !== 200) {
options.error(xhr);
}
options.complete(xhr);
}

function parseParam(params) {
let params_arr = [];
for (let name in params) {
params_arr.push(name + '=' + params.name);
}
return params_arr.join('&');
}
}

jQuery的Ajax

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function getReturnData(_path, _param, _type, _fn, _errorFn, async) {
if (async === undefined) {
async = true;
}
var _url = getContextPath() + _path;
$.ajax({
url: _url,
type: _type,
async: async,
contentType: 'application/json;charset=utf-8',
data: _param,
success: function (data) {
_fn.call(this, data, data);
},
error: function (err) {
_errorFn.call(this, err);
removeModal();
}
});
}

评论