Ajax异步请求

1、异步请求的get请求的完整五步曲

        //1.0创建一个异步对象
            var xhr = new XMLHttpRequest();
            //2.0打开连接
            //           请求方式    请求路径     是否异步
            xhr.open("get", "/P02Time.ashx", true);
            //3.2设置请求报文头(清除缓存)
            xhr.setRequestHeader("If-Modified-Since", 0);//浏览器设置为当前请求不缓存
            //4.0设置回调函数(约定数据响应回来以后操作)
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    //得到从服务器拿回来的数据
                    var text = xhr.responseText;
                    document.getElementById("div").innerHTML = text;
                }
            }
            //5.0发送请求
            xhr.send();

2、异步请求的的post请求的完整五步曲

        //1.0创建对象
            var xhr = new XMLHttpRequest();
            //2.0打开连接
            xhr.open("post", "/P02Time.ashx", true);
            //3.0设置请求报文头
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

            //4.0设置回调函数
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var text = xhr.responseText;
                    document.getElementById("div").innerHTML = text;
                }
            }
            //5.0发送请求
            xhr.send("id=1&name=2");
原文地址:https://www.cnblogs.com/qidakang/p/4781009.html