首页 > 代码库 > 原生Ajax

原生Ajax

    <script type="text/javascript">        //1 创建xhr对象        var xhr = createXHR();        function createXHR() {            var request;            if (typeof (XMLHttpRequest) == "undefined") {                //ie老版本中创建的方式                request = new ActiveXObject("Microsoft.XMLHTTP");            } else {                //支持标准的浏览器创建的方式                request = new XMLHttpRequest();            }            return request;        }        window.onload = function () {            document.getElementById("txt").onkeyup = function () {                var txt = this;                //判断是否有mydiv                var mydiv = document.getElementById("mydiv");                if (mydiv) {                    document.getElementById("container").removeChild(mydiv);                }                if (this.value.length <= 0) {                    return;                }                //2                xhr.open("get", "defalut.ashx?wd=" + this.value, true);                //3                xhr.onreadystatechange = function () {                    if (xhr.readyState == 4)                    {                        if (xhr.status == 200) {                            var r = xhr.responseText;                            //把字符串转换成数组对象                            var array = eval(r);                            //动态生成div                            var div = document.createElement("div");                            div.id = "mydiv";                            document.getElementById("container").appendChild(div);                            //                            var ul = document.createElement("ul");                            div.appendChild(ul);                            for (var i = 0; i < array.length; i++) {                                var li = document.createElement("li");                                li.innerHTML = array[i];                                ul.appendChild(li);                                li.onmouseover = function () {                                    this.style.backgroundColor = "red";                                   txt.value =  this.innerHTML;                                }                                li.onmouseout = function () {                                    this.style.backgroundColor = "";                                }                            }                        }                    }                }                //4                xhr.send();            }        }    </script>
View Code

 

原生Ajax