封装ajax
在我们需要发送get类型的ajax请求时,最简单的需要变化的就是我们请求的地址,还有请求成功后对于数据的操作。因此,可以把这两项作为参数传递到函数中,代码如下:
function getAjax1(httpUrl, callBack) {
// 1.创建Ajax对象
var xhr = new XMLHttpRequest();
//2.设置请求的方法和路径,相对路径与绝对路径都可
xhr.open('GET', httpUrl);
// 3.发送数据
xhr.send();
//4.监听后台是否返回数据
xhr.onreadystatechange = function() {
if (xhr.status == 200 && xhr.readyState == 4) {
// 5.处理数据
callBack(xhr);
}
}
};
在页面中进行调用:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="./js/getAjax.js"></script>
<script>
getAjax1('./abc.txt', function(xhr) {
var h1 = document.createElement('h1');
h1.innerHTML = xhr.response;
document.body.appendChild(h1);
});
getAjax1('https://api.apiopen.top/musicRankingsDetails?type=1', function(xhr) {
console.log(xhr);
});
</script>
</body>
</html>
在第二个请求函数中的地址,带有?type=1,正常来讲,这个也是需要不断变化的,因此,我们可以对其做进一步封装,定义一个拼接请求参数的函数,再调用这个函数就可以了。
function parseData(data) {
var str = ''
for (var key in data) {
str = str + key + '=' + data[key] + '&';
}
return str.substr(0, str.length - 1);
};
function getAjax2(httpUrl, data, callBack) {
// 1.创建Ajax对象
var xhr = new XMLHttpRequest();
//2.设置请求的方法和路径,相对路径与绝对路径都可
xhr.open('GET', httpUrl + '?' + parseData(data));
// 3.发送数据
xhr.send();
//4.监听后台是否返回数据
xhr.onreadystatechange = function() {
if (xhr.status == 200 && xhr.readyState == 4) {
// 5.处理数据
callBack(xhr);
}
}
};
在页面中调用:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="./js/getAjax.js"></script>
<script>
var data = {
type: 1
}
getAjax2('https://api.apiopen.top/musicRankingsDetails/', data, function(xhr) {
console.log(xhr);
});
</script>
</body>
</html>