Ajax 异步无刷新技术原生Ajax的实现流程 得到XMLHttpRequest对象
- var xhr = new XMLHttpRequest();打开请求
- xhr.open(method,url,async);
- method:请求方式,通常是GET|POST
- url:请求地址
- async:是否异步。如果是true,表示异步,false表示同步发送请求
- xhr.send(params);
- params:请求时需要传递的参数
- 如果是GET请求,设置null(GET请求设置在url后面)
- 如果是POST请求,无参数设置为null,有参数则设置参数接受响应
- xhr.status xiangy状态(状态码)
- xhr.responseText 得到响应结束 同步请求
<script type="text/javascript">/*** 同步请求*/function test01() {//得到XMLHttpRequest对象var xhr = new XMLHttpRequest();console.log(xhr.readyState);//准备状态//打开请求xhr.open('GET','js/data.json',false); //同步请求console.log(xhr.readyState);//准备状态// 发送请求xhr.send(null);console.log(xhr.readyState);//准备状态// 判断响应状态if(xhr.status == 200){console.log(xhr.readyState);//准备状态// 获取响应结果console.log(xhr.responseText);}else{console.log("状态码:"+xhr.status+",原因:"+xhr.responseText);}console.log("同步请求。。。。");}// 同步请求test01();</script>
异步请求
<script type="text/javascript">/*** 异步请求*/function test02(){//得到XMLHttpRequest对象var xhr = new XMLHttpRequest();// console.log(xhr.readyState);//准备状态//打开请求xhr.open('GET','js/data.json',true); //异步请求// console.log(xhr.readyState);//准备状态// 发送请求xhr.send(null);/*** 由于是异步请求,所以需要知道后台已经将请求处理完毕,才能获取响应结果* 通过监听readyState的变化来得知后面的处理状态(4表示完全处理成功)*xhr.onreadystatechange = function(){* }*/xhr.onreadystatechange = function(){// 当readySate的值为4时,表示结果成功响应if( xhr.readyState == 4){// 判断响应状态if(xhr.status == 200){// console.log(xhr.readyState);//准备状态// 获取响应结果console.log(xhr.responseText);}else{console.log("状态码:"+xhr.status+",原因:"+xhr.responseText);}} }// console.log(xhr.readyState);//准备状态console.log("异步请求。。。。");}// 异步请求test02();</script>