封装ajxa四个个步骤
- 创建ajax对象var xhr = new XMLHttpRequest();
- 设置数据库地址 xhr.open()
- 发送请求xhr.send();
- 后台数据库响应状态 xhr.status == 200 && xhr.readyState == 4
function getAjax(url, data, callbackFn) {
var xhr = new XMLHttpRequest()
xhr.open("GET", url + parsedata(data))
// url地址字符串拼接
xhr.send()
xhr.onreadystatechange = function () {
if (xhr.status == 200 && xhr.readyState == 4) {
callbackFn(xhr)
//回调函数=方便填写回调后的方法需求
}
}
// 接口数据解析返回给ajaxa
function parsedata(data) {
var str = "?"
for (var key in data) {
str = str + key + "=" + data[key] + "&"
}
return str.slice(0, str.length - 1)
}
}
<script src="./getAjax.js"></script>
<script>
var fn = function (xhr) {
console.log(xhr)
var datiObj = JSON.parse(xhr.response)
console.log(datiObj)
}
var data = {
page: 1,
count: 10,
type: "video",
}
var apI = "https://api.apiopen.top/getJoke"
getAjax(apI, data, fn)
</script>