Use object 315 FormData


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>

<body>
    <!-- 创建普通的html表单 -->
    <form id="form">
        <input type="text" name="username">
        <input type="password" name="password">
        <input type="button" id="btn" value="提交">
    </form>

    <script type="text/javascript">
        var btn = document.getElementById('btn'); // 获取按钮
        var form = document.getElementById('form'); // 获取表单

        // 为按钮添加点击事件
        btn.onclick = function() {
            var formData = new FormData(form); // 将普通的html表单转换为表单对象
            var xhr = new XMLHttpRequest(); // 创建ajax对象
            xhr.open('post', 'http://localhost:3000/formData'); // 对ajax对象进行配置
            xhr.send(formData); // 发送ajax请求

            // 监听xhr对象下面的onload事件
            xhr.onload = function() {
                // 对象http状态码进行判断
                if (xhr.status == 200) {
                    console.log(xhr.responseText);
                }
            }
        }
    </script>
</body>

</html>

Guess you like

Origin www.cnblogs.com/jianjie/p/12347740.html