转圈圈

ajax

ajax

  1. get 方法

    // 请求数据
    function get1(string) {
      // 兼容写法
      let xhr;
      if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
      } else {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
      }
      xhr.onreadystatechange = function() {
        // async 为true时,需要指定onreadystatechange事件中的执行函数
        if (xhr.readyState === 4 && xhr.status === 200) {
          console.log(xhr.responseText);
        }
      };
      xhr.open("GET", "./index.html" + string, true); // true 代表异步执行
      xhr.send();
    }
    
    // 请求数据,从新加载而不是从缓存中读取
    // 改变请求url,加Math.random()
    function get2() {
      let xhr = new XMLHttpRequest();
      xhr.onreadystatechange = function() {
        // async 为true时,需要指定onreadystatechange事件中的执行函数
        if (this.readyState === 4 && this.status === 200) {
          console.log(this.responseText);
        }
      };
      xhr.open("GET", "./index.html?t=" + Math.random(), true);
      xhr.send();
    }
    
    // get 提交信息,信息?key=value
    function get3() {
      let xhr = new XMLHttpRequest();
      xhr.open("GET", "./index.html?name=achilles&age=18", false);
      xhr.send();
      // async 为false的时候,不用编写 onreadystatechange 执行函数,直接把代码放到send 后面即可
      console.log(this.responseText);
    }
    
  2. post 方法

    // 请求数据
    function post1() {
      let xhr = new XMLHttpRequest();
      // async 为true时,需要指定onreadystatechange事件中的执行函数
      xhr.onreadystatechange = function() {
        if (this.readyState === 4 && this.status === 200) {
          console.log(xhr.responseText);
        }
      };
      xhr.open("POST", "./index.html", true);
      xhr.send();
    }
    
    // 提交数据
    function post2() {
      let xhr = new XMLHttpRequest();
      // async 为true时,需要指定onreadystatechange事件中的执行函数
      xhr.onreadystatechange = function() {
        if (this.readyState === 4 && this.status === 200) {
          console.log(xhr.responseText);
        }
      };
      xhr.open("POST", "./index.html", true);
      // 设置http请求头
      xhr.setRequestHeader("Content-Type", "application/json");
      // 发送的数据
      xhr.send("name=achilles&age=19");
    }
    
posted @ 2019-03-28 22:23  rosendolu  阅读(96)  评论(0编辑  收藏  举报