简易的ajax
get请求
//get请求
const xhr = new XMLHttpRequest()
xhr.open("GET","/api",false)//false表示请求方式为异步
xhr.onreadystatechange = function () {
if(xhr.readyState === 4){
if(xhr.status === 200){
console.log(JSON.parse(xhr.responseText))//转化成json格式
}
}
}
xhr.send(null)
post请求
const xhr = new XMLHttpRequest()
xhr.open("POST","/login",false)
xhr.onreadystatechange = function () {
if(xhr.readyState === 4){
if(xhr.status === 200){
console.log(JSON.parse(xhr.responseText))
}
}
}
const postData = {
username:'张三',
password:'123456'
}
xhr.send(JSON.stringify(postData))//发送字符串
xhr.readyState状态
- 0-(未初始化)还没有调用send()方法
- 1-(载入)已调用send()方法,正在发送请求
- 2-(载入完成)send()方法执行完成,已经接收到全部响应内容
- 3-(交互)正在解析响应内容
- 4-(完成)响应内容解析完成,可以在客户端调用
xhr.status
- 2xx-表示成功处理请求,如200
- 3xx-重定向,浏览器直接跳转,如301(永久重定向),302(临时重定向),304(资源未改变)
- 4xx-客户端请求错误,如404(请求地址有错误),403(客户端没有权限)
- 5xx-服务器端错误
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。