使用Javascript实现ajax示例

使用原始的javascript实现ajax

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <script type="text/javascript">

        function run() {

            var xmlHttpReq = null;
            if (window.ActiveXObject) {
                //IE5,IE6是以ActiveXObject的方式引入XMLHttpRequest对象的
                xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
            } else if (window.XMLHttpRequest) {
                //除IE5和IE6以外的浏览器
                //XMLHttpRequest是window的子对象
                实例化一个XMLHttpRequest对象
                xmlHttpReq = new XMLHttpRequest();
            }

            xmlHttpReq.open("get", "Handler1.ashx", true);
            
            //一旦readyState值改变,将会调用该函数
            xmlHttpReq.onreadystatechange = function () { //设置回调函数
                if (xmlHttpReq.readyState==4) {
                    if(xmlHttpReq.status==200){
                        alert(xmlHttpReq.responseText);
                        document.getElementById('h3').innerHTML = xmlHttpReq.responseText;

                    }
                }
            }
            
            //因为使用get方法提交,这里可以使用null作为参数调用。
            xmlHttpReq.send(null);//在IE11下不用写null也调用成功了。
        }
    </script>
</head>
<body>
    <input type="button" value="ajax提交" onclick="run();" />
    <h3 id="h3"></h3>
</body>
</html>

原文地址:https://www.cnblogs.com/liuguangyin/p/6607520.html