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"&gt;</input&gt;
   <input type="password" placeholder="密码" name="pwd"&gt;</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>

原文地址:https://blog.csdn.net/sxp19980829/article/details/129687286

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_43292.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注