ajax请求详解

ajax的基础是XMLHttpRequest

1、需要新建对象

let xhr = new XMLHttpRequest();

2、向服务器发送请求

xhr.open(method,url,async);  //method定义请求post还是get方法    url定义请求路径async定义是否异步

xhr.send(string); // string仅用于post请求

注意:这两个方法必须同时搭配,像亲兄弟一样,缺一不可

3、获取服务器响应

xhr.onreadystatechange = function(){ 

 if(xhr.readystate == 4 && xhr.state == 200){

   console.log(xhr.responseText);   //当该状态下时成功获取到数据

 } 


}

在请求期间,readtstate会对应 (0-4)5个数值,每次数值变化都会触发onreadystatechange方法,注意此时又一个onload方法只有在reasystate = 4 时才会触发

 

 

你可能感兴趣的:(前端开发技巧)