form表单提交数据的两种方式——submit直接提交、AJAX提交

submit提交

form表单本身提供action属性,在action属性中填写数据提交地址后,点击submit类型的按钮即可将数据提交至指定地址,代码如下:

<form action="127.0.0.1:3001/register" method="post"  >
   <input type="text" placeholder="昵称" name="username"></input>
   <input type="email" placeholder="邮箱" name="email"></input>
   <input type="password" placeholder="密码" name="pwd"></input>
   <input type="submit">注册</input>
</form>
注意:
method指定请求方式
每个input表单项需要有name属性

通过上述方式提交表单数据后,会发生页面跳转,跳转至action所指定的地址,很难满足开发需求。若要提交数据后不跳转,可以尝试通过ajax提交数据。

AJAX提交

form表单不填写action属性,并且在提交时阻止表单的默认行为,获取到表单数据后通过ajax的方式发送给后端,代码如下:

<!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" method="post"  >
        <input type="text" placeholder="昵称" name="username"></input>
        <input type="email" placeholder="邮箱" name="email"></input>
        <input type="password" placeholder="密码" name="pwd"></input>
        <button id="btn" type="submit">注册</button>
     </form>
</body>
<script>
    document.getElementById('btn').onclick=function(e){
        e.preventDefault()

        let form = document.getElementById("form");
        form.addEventListener("submit", function (event) {
          
            let XHR = new XMLHttpRequest();
            // 将表单数据转为Formdat格式
            let FD  = new FormData(form);
            XHR.open("POST", "http://127.0.0.1:3001/register");
            // XHR.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
            XHR.send(FD)
            XHR.onreadystatechange=function(){
                // do something according to response
            }
        })
    }
</script>
</html>

猜你喜欢

转载自blog.csdn.net/sxp19980829/article/details/129687286