• js【详解】ajax (含XMLHttpRequest、 同源策略、跨域、JSONP)


    ajax 的核心API – XMLHttpRequest

    get 请求

    // 新建 XMLHttpRequest 对象的实例
    const xhr = new XMLHttpRequest();
    // 发起 get 请求,open 的三个参数为:请求类型,请求地址,是否异步请求( true 为异步,false 为同步)
    xhr.open("GET", "/data/test.json", false);
    
    // 定义 xhr 状态改变的处理函数
    xhr.onreadystatechange = function () {
      // xhr 的 readyState 属性变为 4
      if (xhr.readyState === 4) {
        // 网络请求返回的状态码为 200
        if (xhr.status === 200) {
          alert(xhr.responseText);
        } else if (xhr.status === 404) {
          // 网络请求返回的状态码为 404
          console.log("404 not found");
        } else {
          console.log("其他情况");
        }
      }
    };
    
    // 发出请求,会触发 xhr 状态的改变
    xhr.send(null);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    post 请求

    // 新建 XMLHttpRequest 对象的实例
    const xhr = new XMLHttpRequest();
    // open 的三个参数为:请求类型,请求地址,是否异步请求( true 为异步,false 为同步)
    xhr.open("POST", "/login", false);
    
    // 定义 xhr 状态改变的处理函数
    xhr.onreadystatechange = function () {
      // xhr 的 readyState 属性变为 4
      if (xhr.readyState === 4) {
        // 网络请求返回的状态码为 200
        if (xhr.status === 200) {
          alert(xhr.responseText);
        } else if (xhr.status === 404) {
          // 网络请求返回的状态码为 404
          console.log("404 not found");
        } else {
          console.log("其他情况");
        }
      }
    };
    
    // 定义 post 请求的参数
    const postData = {
      userName: "朝阳",
      password: "xxx",
    };
    
    // 发出请求 -- 参数需转为字符串
    xhr.send(JSON.stringify(postData));
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    XMLHttpRequest 的 readyState 属性

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

    XMLHttpRequest 的 status 属性

    http 请求的状态码,详见
    https://blog.csdn.net/weixin_41192489/article/details/136446539

    同源策略

    ajax 请求地址的 协议、域名、端口 必须和当前网页的地址相同!

    • 浏览器中的 ajax 请求才有同源策略限制
    • 图片、css文件、js文件的加载,没有同源策略限制,应用如下:
      • 图片用于使用第三方统计服务完成统计打点(如统计网页浏览量)
      • 使用 CDN 加速图片、css文件、js文件