ajax.js
function resolveData(obj) {
let arr = []
for (let key in obj) {
arr.push(`${key}=${obj[key]}`)
}
return arr.join('&')
}
// console.log(resolveData({id:1,name:'小明'}))
function myAjax({ method, url, data, success }) {
let xhr = new XMLHttpRequest()
method = method.toLowerCase()
switch (method) {
case 'get':
xhr.open(method, `${url}?${resolveData(data)}`)
xhr.send()
break
case 'post':
xhr.open(method,url)
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
xhr.send( resolveData(data))
break
default:
break
}
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
let result = JSON.parse(xhr.responseText)
success(result)
}
}
}
ajax.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./ajax.js"></script>
</head>
<body>
<script>
myAjax({
method: 'GET',
url: 'http://www.liulongbin.top:3006/api/getbooks',
data: {
id: 1
},
success(res) {
console.log(res)
}
})
myAjax({
method: 'POST',
url: 'http://www.liulongbin.top:3006/api/addbook',
data: {
bookname: '明朝那些事er',
author: '当年明月',
publisher: '天津教育出版社'
},
success(res) {
console.log(res)
}
})
</script>
</body>
</html>