327 使用Ajax实现提交表单

<!DOCTYPE html>
<html>

<head>
    <title>表单中使用Ajax</title>
    <meta charset="utf-8" />
</head>

<body>
    <!-- action、method属性可不写,submit按钮改为button,input输入框要有name属性 -->
    <form id="myform" name="myform" action="03.php" method="post" enctype="application/x-www-form-urlencoded">
        用户名: <input type="text" id="user" name="user"><br> 
        密码: <input type="text" id="pwd" name="pwd"><br>
        <input type="button" id="btn" value="登录">
    </form>

    <script>
        /*
         * <form>表单元素,存在submit按钮,提交表单
         * 使用Ajax提交表单的话,不需要使用submit
         * * 将submit按钮修改为button
         */
        // 1. 为button按钮绑定onclick事件
        var btn = document.getElementById("btn");

        // 使用Ajax实现提交表单
        btn.onclick = function() {
            // send()发送用户名和密码
            var user = document.getElementById("user").value;
            var pwd = document.getElementById("pwd").value;
            var xhr = getXhr();
            xhr.open("post", "03.php");
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

            xhr.send("user=" + user + "&pwd=" + pwd); //后面的user、pwd是变量
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var data = xhr.responseText;
                    console.log(data);
                }
            }
        }

        function getXhr() {
            var xhr = null;
            if (window.XMLHttpRequest) {
                xhr = new XMLHttpRequest();
            } else {
                xhr = new ActiveXObject("Microsoft.XMLHttp");
            }
            return xhr;
        }
    </script>
</body>

</html>

猜你喜欢

转载自www.cnblogs.com/jianjie/p/12360304.html