AJAX 基础

来源:互联网 发布:淘宝微淘在哪里 编辑:程序博客网 时间:2024/06/05 03:45
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script type="text/javascript">
        var xhr = null;
        //创建xhr
        function createXHR() {
            if (window.XMLHttpRequest) {//DOM2浏览器
                xhr = new XMLHttpRequest();
            } else if (window.ActiveXObject) {//IE
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
        }
        //发送请求
        function ajax() {
            createXHR();
            xhr.open("POST", "http://localhost:8080/ajax", true);//method方式最好是大写,firefox敏感,如GET、POST
            xhr.onreadystatechange = execute;
            xhr.send(null);
        }
        //回调函数
        function execute() {
            if (xhr.status === 200 && xhr.readyState === 4) {
                console.info(xhr.responseText);
                document.getElementsByTagName("p")[0].innerHTML = xhr.responseText;
            }
        }
//        ajax();
    </script>
</head>
<body>
    <p>hello</p>
    <input type="button" value="变" onclick="ajax()" />
</body>
</html>
0 0
原创粉丝点击