封装 Ajax
因为Ajax 使用起来比较麻烦,主要就是参数问题,比如到底使用GET 还是POST;到
底是使用同步还是异步等等,我们需要封装一个Ajax 函数,来方便我们调用。
封装支持接收来自服务端的数据,不可以发送数据到服务端
/**
* 此封装只支持接收来自服务端的数据,不可以发送数据到服务端
*/
function ajax(obj) {
var xhr = new XMLHttpRequest();
obj.url = obj.url + '?rand=' + Math.random();
xhr.open(obj.method, obj.url, obj.async);
xhr.send(null);
if (obj.async === false) {
callback();
}
if (obj.async === true) {
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
callback();
}
};
}
function callback () {
if (xhr.status == 200) {
obj.success(xhr.responseText); //回调
} else {
alert('数据返回失败!状态代码:' + xhr.status + ',状态信息:' + xhr.statusText);
}
}
}
把上面的代码封装在ajax2.js中,在页面上引入该文件。
<!DOCTYPE html>
<html>
<head>
<title>Ajax的封装</title>
<meta charset="utf-8">
<script src="ajax2.js"></script>
</head>
<body>
<button id="btn">调用Ajax</button>
<script>
document.getElementById("btn").onclick=function(){
ajax({
method : 'get',
url : 'http://localhost:3000/api/2',
success : function (text) {
alert(text);
},
async :false
});
};
</script>
</body>
</html>
7.2 封装支持接收来自服务端的数据,又可以发送数据到服务端
function ajax(obj) {
var xhr = new XMLHttpRequest();
obj.url = obj.url + '?rand=' + Math.random();
obj.data = params(obj.data);
if (obj.method === 'get') {
obj.url = obj.url.indexOf('?') == -1 ? obj.url + '?' + obj.data : obj.url + '&' + obj.data;
}
if (obj.async === true) {
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
callback();
}
};
}
xhr.open(obj.method, obj.url, obj.async);
if (obj.method === 'post') {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(obj.data);
} else {
xhr.send(null);
}
if (obj.async === false) {
callback();
}
function callback () {
if (xhr.status == 200) {
obj.success(xhr.responseText); //回调
} else {
alert('数据返回失败!状态代码:' + xhr.status + ',状态信息:' + xhr.statusText);
}
}
}
//名值对编码
function params(data) {
var arr = [];
for (var i in data) {
arr.push(encodeURIComponent(i) + '=' + encodeURIComponent(data[i]));
}
return arr.join('&');
}
希望能够帮到你!