提交表单后跳转到想要的页面

表单提交的问题一直困扰着我这个新手,现在也算学习了不少,解决了我现在有的问题 —— 提交了表单之后将数据给到后台并且让前端页面跳转到想要的页面或出现想要的内容。

用到了 jQuery Form Plugin,表单提交的第三方插件,为了更方便的管理和提交表单。(官网:http://plugins.jquery.com/form/

借鉴:https://blog.csdn.net/m0_37505854/article/details/79639046(主要)

https://www.cnblogs.com/hudandan/p/5912336.html

我在这只写如何提交并显示想要的内容(跳转到页面同理),其中有好多概念什么的,我没列举出来,不了解的可以先看一遍官网的文档或其他的相关文档,有个大概的了解之后再去参考别人写的代码,就会好理解很多,我就是这样做的。

1 引入 jQuery.js 和 jquery-form.js:

<script src="sources/jquery-1.9.1.js"></script>
<script src="sources/jquery-form.js"></script>

2 HTML 里写的代码就是很普通的表单控件:

<div id="showForm">
    <form action="/postform" method="post" id="ajaxForm">   <!--postform 是用于提交的地址-->
        <input type="text" name="user">
        <input type="number" name="age">
        <button type="submit">提交</button>
    </form>
</div>

3 js 代码:

重点就是 js 代码的部分了,这是实现表单提交之后的显示的!

<script>
    $(      //页面加载完执行
        $("#ajaxForm").on("submit",function () {    //表单提交时监听提交事件
            $(this).ajaxSubmit(options);    //当前表单执行异步提交,optons 是配置提交时、提交后的相关选项
            return false;   //  必须返回false,才能跳到想要的页面
        })
    )
    //配置 options 选项
    var options = {
        url: "/postform",       //提交地址:默认是form的action,如果申明,则会覆盖
        type: "post",           //默认是form的method(get or post),如果申明,则会覆盖
        success: successFun,    //提交成功后的回调函数,即成功后可以定页面跳到哪里
        dataType: "json",       //接受服务端返回的类型
        clearForm: true,        //成功提交后,清除所有表单元素的值
        resetForm: true,        //成功提交后,重置所有表单元素的值
        timeout: 3000           //设置请求时间,超过该时间后,自动退出请求,单位(毫秒)
    }
    //设置提交成功后返回的页面
    function successFun(data,status) {
        $("#showForm").html(data.msg);      //提交表单后从后台接收到的返回来的数据,我保存到了msg里
        // $("#showForm").html("或者这里可以直接写想要显示的内容")
    }
</script>

我用的是 nodejs (非必须):

app.post("/postform",function (req, res) {
        console.log(req.body);
        userLink.create({
            "name": req.body.user,
            "age": req.body.age
        },function (err) {
            if(err) throw err;
            res.status(200).json({success: true,msg: "提交成功,这是你想要返回的页面。"});
        })
    })

其实写 nodejs 是因为要给一个可以提交过去的地址,一般都是后台给的,为了记录就写上了。

有不足之处欢迎指正,共同学习。

(⌒▽⌒)

 

猜你喜欢

转载自blog.csdn.net/KLbluegreen/article/details/82659676