1. // get /data/test.json
  2. const xhr = new XMLHttpRequest()
  3. xhr.open("GET", "/data/test.json", true) // true 异步请求
  4. xhr.onreadystatechange = function () {
  5. if(xhr.readyState === 4) {
  6. if(xhr.status === 200) {
  7. console.log(
  8. JSON.parse(xhr.responseText)
  9. )
  10. alert(xhr.responseText)
  11. }
  12. }
  13. }
  14. xhr.send(null)
  1. // post
  2. const xhr = new XMLHttpRequest()
  3. xhr.open("POST", "/login", true) // true 异步请求
  4. xhr.onreadystatechange = function () {
  5. if(xhr.readyState === 4) {
  6. if(xhr.status === 200) {
  7. console.log(
  8. JSON.parse(xhr.responseText)
  9. )
  10. alert(xhr.responseText)
  11. }
  12. }
  13. }
  14. const postData = {
  15. userName: 'zhangsan',
  16. password: 'xx'
  17. }
  18. xhr.send(JSON.stringify(postData))

xhr.readyState

  • 0- (未初始化)还没有调用send()方法
  • 1-(载入)已调用send()方法,正在发送请求
  • 2-(载入完成)send()方法执行完成,已经接收到全部相应内容
  • 3- (交互)正在解析响应内容
  • 4- (完成)响应内容解析完成,可以在客户端调用

    xhr.status

  • 2xx- 表示请求成功,如200

  • 3xx- 表示重定向, 浏览器直接跳转,如301 302 304
  • 4xx- 表示客户端请求错误, 如403 404
  • 5xx- 表示服务端错误