<script>
/* GET请求 */
function testGet() {
axios({
url:'http://localhost:3000/posts',
method:'GET',
params:{
id:2,
xxx:"abc"
}
}).then(response=>{
console.log(response);
},error=>{
console.log(error.message);
})
}
/* Post请求 */
function testPost() {
axios({
url:'http://localhost:3000/posts',
method:'POST',
data:{
"title": "json-server----","author": "typicode----"
}
}).then(response=>{
console.log(response);
},error=>{
console.log(error.message);
})
}
/* PUT请求 */
function testPut() {
axios({
url:'http://localhost:3000/posts/2',
method:'PUT',
data:{
"title": "json-server666","author": "typicode666"
}
}).then(response=>{
console.log(response);
},error=>{
console.log(error.message);
})
}
/* Delete请求 */
function testDelete() {
axios({
url:'http://localhost:3000/posts/6',
method:'DELETE',
data:{
"title": "json-server----","author": "typicode----"
}
}).then(response=>{
console.log(response);
},error=>{
console.log(error.message);
})
}
/* 封装一个ajax基于axios */
function axios({
url,
method,
params={},
data={}
}) {
// 返回一个promise对象
return new Promise((resolve,reject)=>{
// 处理method 转换为大写
method = method.toUpperCase()
let queryString = ''// 处理query参数(拼接到url上) id=1&xxx=abc
Object.keys(params).forEach(v=>{
queryString+=`${v}=${params[v]}&`
})
if(queryString){
queryString = queryString.substring(0,queryString.length-1)
url += '?' + queryString
}
// 1. 执行异步ajax请求
const request = new XMLHttpRequest()// 1.1. 创建xhr对象
request.open(method,url,true)// 1.2. 打开链接(初始化请求, 没有请求)
// 1.3. 发送请求
if(method==='GET'||method==='DELETE'){
request.send()
}else if(method==='POST'||method==='PUT'){
request.setRequestHeader('Content-Type','application/json;charset=utf-8')// 告诉服务器请求体的格式是json
request.send(JSON.stringify(data)) // 发送json格式请求体参数
}
// 1.4 绑定状态改变的监听
request.onreadystatechange = function(){
// 如果请求没有完成, 直接结束
if(request.readyState!==4){
return
}
// 如果响应状态码在[200,300)之间代表成功, 否则失败
const {status,statusText} = request
// 2. 如果调用成功了, 调用 resolve
if(status>=200 && status<=299){
// 准备结果数据对象response
const response = {
data:JSON.parse(request.response),// 响应体(装换为json格式)
status,// 响应状态码
statusText// 响应文本
}
resolve(response)
}else{ // 3. 如果调用失败了, 调用 reject
reject(new Error('request error status' + status))
}
}
})
}
</script>