Ajax

Ajax创建与响应

var xhr = new XMLHttpRequest();//创建Ajax
// readyState获取状态的值
console.log(xhr.readyState);//=>0 初始化请求代理对象
xhr.open("GET","test.php");//请求地址
console.log(xhr.readyState);//=>1 open()被调用后,建立一个与服务端的连接
xhr.send();//发送请求
// onreadystatechange状态发生改变就执行该事件
xhr.addEventListener("readystatechange",function(){
    if(this.readyState == 2){
        // =>2 可以获取响应报文的响应头
        // getAllResponseHeaders()响应头
        console.log(this.getAllResponseHeaders());
        // date: Thu, 13 Sep 2018 01:04:51 GMT
        // server: Apache/2.4.34 (Win64) OpenSSL/1.0.2o PHP/7.2.9
        // connection: Keep-Alive
        // x-powered-by: PHP/7.2.9
        // content-length: 9
        // keep-alive: timeout=5, max=45
        // content-type: text/html; charset=UTF-8
        console.log(this.getResponseHeader("date"));//获取单个响应头
    }else if(this.readyState == 3){
        // =>3 正在下载响应报文的响应体
    }else if(this.readyState == 4){
        // =>4 已经接收到了响应报文的响应体
        // responseText 响应体
        console.log(this.responseText);
    }
});

onload()

var xhr = new XMLHttpRequest();
xhr.open("GET","test.php");
xhr.send();
xhr.onload = function(){//HTML5的事件.低版本不支持
    console.log(this.readyState);
    console.log(this.responseText);
}

 

posted @ 2018-09-13 10:34  黄强小菜鸟  阅读(168)  评论(0编辑  收藏  举报