ajax.js
const ajax = {}
ajax.request = function (url,data,method = 'POST') {
return new Promise((resolve, reject) => {
const xmlHttp = new XMLHttpRequest()
xmlHttp.open(method,method === 'POST' ? url : `${url}?data=${JSON.stringify(data)}`)
xmlHttp.setRequestHeader('Content-Type', 'application/json;charset=UTF-8')
xmlHttp.send(method === 'POST' ? JSON.stringify(data) : null)
xmlHttp.onreadystatechange = function () {
if(xmlHttp.readyState === 4) {
if(xmlHttp.status === 200) {
console.log(JSON.parse(xmlHttp.responseText))
resolve(JSON.parse(xmlHttp.responseText))
}
if(xmlHttp.status === 404) {
reject(xmlHttp.responseText)
}
}
}
})
}
export default ajax
test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script type="module">
import ajax from './ajax.js'
ajax.request('http://127.0.0.1:3000/test',{
x: [1,2],
y: 2
},'GET').then(res => {
console.log(res)
})
ajax.request('http://127.0.0.1:3000/test',{
x: [1,2],
y: 2
},'POST').then(res => {
console.log(res)
})
</script>
</body>
</html>
app.js
原生ajax会有跨域问题,后台要允许跨域访问,这里是express框架
app.all('*', function (req, res, next) {
console.log('收到了请求')
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Content-Type')
res.header('Access-Control-Allow-Methods', '*')
res.header('Content-Type', 'application/json;charset=utf-8')
next()
})
app.post('/test',function (req,res,next) {
console.log(req.body)
res.json({
a: 1,
b: 2
})
})
app.get('/test',function (req,res,next) {
console.log(req.query)
res.json({
a: 1,
b: 2
})
})
以上就是原生ajax的简单运用,在一些轻量级的应用上可以自己封装一个小的ajax函数,而不用引入第三方的包,从而使代码的体积更小化