关于ajax:ajax的核心APIXMLHttpRequest

繁难的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-服务器端谬误

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理