原生AJAX

function ajaxRequest(method, data, withCookie){
  let xhr = new XMLHttpRequest();
  if(withCookie===true){  //允许发送Cookie
     xhr.withCredentials = true;
  }
  let res;
  //httpRequest.readyState: 
  /*0 - UNSENT 代理创建,尚未调用open(); 
    1 - OPENED open()已调用; 
    2 - HEADERS_RECEIVED send()已调用,获得头部状态; 
    3 - LOADING 下载中; 
    4 - DONE 下载完成,responseText属性数据完整.*/
  xhr.onreadystatechange = function(e){
    if(this.readyState == 4 && this.status == 200){
       console.log("success");
       res = this.responseText;
    }
  }
  if(method.toLowerCase() === "get"){
     xhr.open("get", "http://XXX.XXX.com/", true);
     xhr.send();
  }
  if(method.toLowerCase() === "post"){
     xhr.open("post", "http://XXX.XXX.com/", true);
     xhr.send(data); //data为"key=value&key2=value2"
  }
  return res;
}

 

posted @ 2020-12-22 18:10  `Duet`  阅读(75)  评论(0编辑  收藏  举报