生于理想

导航

FormData对象的使用方法

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <form id="form">
        <input type="text" name="username">
        <input type="password" name="password">
        <input type="button" value="提交" id="btn">
    </form>
    <script>
        var btn = document.getElementById('btn');
        var form = document.getElementById('form');
        btn.onclick = function() {
            //将普通表单转换为form表单
            var formData = new FormData(form);
            var xhr = new XMLHttpRequest();
            xhr.open('post', 'http://localhost:3000/formData');
            xhr.send(formData);
            xhr.onload = function() {
                if (xhr.status == 200) {
                    console.log(xhr.responseText);
                }
            }
        }
    </script>
</body>

</html>

 

posted on 2022-09-29 19:38  生于理想  阅读(31)  评论(0)    收藏  举报