1. 主页
  2. 文档
  3. Ajax
  4. FormDate
  5. FormDate案例代码

FormDate案例代码

<!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="login" action="https://www.imooc.com/api/http/search/suggest?words=js" method="POST" enctype="multipart/form-data">
        <input type="text" name="username" id="user" value="" />
        <input type="password" name="pass" id="pass" value="" />
        <input type="submit" name="submit" id="submit" value="登陆">
    </form>
    <script>
        var fm = document.getElementById("login");
        var us = document.getElementById("user");
        var ps = document.getElementById("pass");
        var su = document.getElementById("submit");


        //阻止表单提交
        //AJAX提交

        su.onclick = function(e) {
            e.preventDefault();

            var xhr = new XMLHttpRequest();
            const url = 'https://www.imooc.com/api/http/search/suggest?words=js';

            xhr.onreadystatechange = function() {
                if (xhr.readyState != 4) return;
                if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
                    console.log(xhr.response);
                }
            };

            // var usn = us.value;
            // var pass = ps.value;
            //使用formdata 组装数据。
            var data = new FormData(fm);
            data.append('wulei', 40);
            data.append('sun', 38);
            //使用FormData就不需要使用 setRequestHeader 创建 Content-Type
            //xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            //不需要组装数据 var data = `username=${usn}&pass=${pass}`;

            // console.log(typeof data);
            // for (var v of data) {
            //     console.log(v);
            // }

            //var data = `username=${usn}&pass=${pass}`;
            xhr.open('POST', url, true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.send(data);

        }
    </script>
</body>

</html>
这篇文章对您有用吗?

我们要如何帮助您?