原生ajax及其请求过程

ajax

Posted by Lan on June 24, 2019

原生ajax及其请求过程,巩固一下基础

创建ajax请求

function getXHR(){
  var xhr = null;
  if(window.XMLHttpRequest) {// 兼容 IE7+, Firefox, Chrome, Opera, Safari
    xhr = new XMLHttpRequest();
  } else if (window.ActiveXObject) {//兼容IE6
    try {
      xhr = new ActiveXObject("Msxml2.XMLHTTP");// 即MSXML3
    } catch (e) {
      try {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");// // 兼容 IE6, IE5,很老的api,虽然浏览器支持,功能可能不完善,故不建议使用
      } catch (e) {
        alert("您的浏览器暂不支持Ajax!");
      }
    }
  }
  return xhr;
}

Ajax请求数据过程

//1.创建ajax对象
var xhr = getXHR();

//2.连接服务器
xhr.open('GET', url/file,true);  //设置请求方式,url,以及是否异步

//get请求,在url定义参数,如www.home.com?name=lan&age=22
//post请求,在发送请求中添加数据,xhr.send(data),data的格式是name=lan&age=23

//3.发送请求
xhr.send();  //发送请求

//post请求一定要添加请求头才行不然会报错
//1.设置的请求编码方式是:
//xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;charset=utf-8');
//data格式:'username=admin&password=admin'
//2.设置的请求编码方式是:
//xhr.setRequestHeader('Content-type', 'aplication/json;charset=utf-8');
//data格式:需要将对象序列化JSON.stringfy(json对象)

//4.接收数据
xhr.onreadystatechange = function() {   //设置回调监听函数
   if(xhr.readyState==4){
        if(xhr.status==200){
            var data=xhr.responseText;
             console.log(data);
   }
};
xhr.onerror = function() {
  console.log("Oh, error");
};

onreadystatechange 事件

onreadystatechange 每当readystate发生改变时,会触发该函数

readystate: 存有xmlHttpRequest的状态,从0到4发生变化

            0:请求未初始化
            1:服务器连接已建立
            2:请求已接收
            3:请求处理中
            4:请求处理完毕

status: 200:ok