[TOC]

XMLHttpRequest

代码演示

          const xhr = new XMLHttpRequest()
        // GET操作 这里的false代表同步
        xhr.open('GET', './text.json', false)
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    alert(xhr.responseText)
                }else{
                    console.log('其他情况');
                }
            }
        }
        xhr.send(null)

        // POST操作 这里的true代表异步
        /* xhr.open('POST', '/login', true)
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    alert(xhr.responseText)
                }else{
                    console.log('其他情况');
                }
            }
        }
        const postData = {
            userName:'zhangsan',
            password:'123456'
        }
        xhr.send(JSON.stringify(postData)) */

xhr.readyState

  • 0-UNSET:尚未调用open方法
  • 1-OPENED:open方法已被调用
  • 2-HEADERS _RECEIVED:send方法已被调用,header已被接收
  • 3-LOADING:下载中,responseText已有部分内容
  • 4-DONE:下载完成

    xhr.status

  • 2XX:表示成功处理请求

  • 3XX:表示重定向,浏览器直接跳转
  • 4XX:客户端请求错误
  • 5XX:服务器端错误

    跨域

    同源策略

  • ajax请求时,浏览器要求当前网页和server必须同源(安全)

  • 同源:协议、域名、端口,三者必须一致
  • 加载图片、CSS、JS可无视同源策略
    • 第十二章 Ajax - 图1
  • 使用

    • 第十二章 Ajax - 图2可用于统计打点,可使用第三方统计服务