首页 > 代码库 > Ajax入门学习原始代码

Ajax入门学习原始代码

<script type="text/javascript">
        window.onload = function () {
            //1、创建xmlhttprequest对象
            var xhr = createXHR();
            function createXHR() {//为了兼容新老IE的版本
                var request;
                if (typeof(XMLHttpRequest)=="undefined") {
                    request = ActiveXObject("Micrpsoft.XMLHTTP");
                } else {
                    request = new XMLHttpRequest();
                }
                return request;
            }
            //Ajax围绕xhr对象操作的
            document.getElementById("btn").onclick = function () {
                //2、初始化xhr
                xhr.open("get", "get1.ashx", true);//参数1:请求方式(get,post);参数2:请求的相对路径;参数3:是否为异步
                //3、注册回调函数
                xhr.onreadystatechange = function () {
                    //readyState属性有5个状态值
                    //0:表示 new 完 xhr
                    //1:表示open完xhr
                    //2:表示send完xhr
                    //3:表示xhr正在接受服务器的数据
                    //4:表示xhr接受完服务器数据
                    if (xhr.readyState==4) {
                        var msg = xhr.responseText;
                        document.getElementById("dv").innerHTML = msg;
                    }
                }
                //4、send
                xhr.send(null);//get方式为NULL
            }
        }
    </script>