简体   繁体   English

提交表单而不重定向到其他页面

[英]To submit a form without redirecting to other page

I have been trying to make an online HTML form, which could submit the form and post the data to the local database. 我一直在尝试制作一个在线HTML表单,该表单可以提交表单并将数据发布到本地数据库。 However, I don't want the page to be redirected to /formfill URL and send the data to DB without redirecting the page. 但是,我不希望页面被重定向到/formfill URL并将数据发送到DB而无需重定向页面。 I have been trying a lot. 我已经很努力了。 However, no luck. 但是,没有运气。 Here is my backend node.js code: 这是我的后端node.js代码:

// require('./../config.js');
const express = require('express');
const path = require('path');
var bodyParser = require('body-parser');
var app = express();
var {
    mongoose
} = require('./models/mongoose.js');
var {
    Data
} = require('./models/form.js');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, '..', 'public')));

app.post('/formfill', function (req, res) {

    var data = new Data({
        name: req.body.name,
        mailId: req.body.mailId
    })

    data.save().then((doc) => {
        res.status(200).send(doc);
    }).catch((e)=>{
        res.status(400).send(e);
    })
})


app.listen(3000, () => {
    console.log("Server is up");
});

Here is my Html form: 这是我的HTML表格:

<form action="/formfill" method="POST" , enctype="application/x-www-form-urlencoded">
  <input class="formfill" type="text" name="name" placeholder="Your name">
  <br>
  <input class="formfill" type="text" name="mailId" placeholder="Your email">
  <br>
  <input id="submit-button" class="formfill sumbit-button" type="submit" value="Submit">
</form>

And here is my JavaScript code, tried with AJAX too: 这是我的JavaScript代码,也尝试过AJAX:

 $(function() { $("#submit-button").submit(function(e) { e.preventDefault(); return false; }) }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form action="/formfill" method="POST" , enctype="application/x-www-form-urlencoded"> <input class="formfill" type="text" name="name" placeholder="Your name"> <br> <input class="formfill" type="text" name="mailId" placeholder="Your email"> <br> <input id="submit-button" class="formfill sumbit-button" type="submit" value="Submit"> </form> 

With AJAX:- 使用AJAX:-

 $(function() { $("#submit-button").submit(function(e) { e.preventDefault(); var formData = new FormData($(this)); $.ajax({ url: '/formfill', type: 'POST', data: formData, async: false, cache: false, contentType: false, processData: false, success: function(response) { console.log(response); } }); }) }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form action="/formfill" method="POST" , enctype="application/x-www-form-urlencoded"> <input class="formfill" type="text" name="name" placeholder="Your name"> <br> <input class="formfill" type="text" name="mailId" placeholder="Your email"> <br> <input id="submit-button" class="formfill sumbit-button" type="submit" value="Submit"> </form> 

All I want to do is submit the form without being redirected to /formfill or refreshing the page. 我要做的就是提交表单,而无需重定向到/formfill或刷新页面。

Replace $("#submit-button").submit(function(e) { with $("#submit-button").closest("form").submit(function(e) { :-) $("#submit-button").submit(function(e) {替换$("#submit-button").closest("form").submit(function(e) { :-)

The preventDefault method seems to work : preventDefault方法似乎有效:

 function customSubmit () { $("#on-btn").attr("disabled", "disabled"); $("#off-btn").removeAttr("disabled"); $("form").on("submit", function (ev) { ev.preventDefault(); console.log($(this).serialize()); }); } function defaultSubmit () { $("#off-btn").attr("disabled", "disabled"); $("#on-btn").removeAttr("disabled"); $("form").off("submit"); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p> <button id="on-btn" type="button" onclick="customSubmit()">Custom submit</button> <button id="off-btn" type="button" onclick="defaultSubmit()" disabled>Default submit</button> </p> <form action="" method="POST"> <input type="text" name="dummy" value="dummy"> <input type="submit" name="submit"> </form> 

async should be true and other details ,,, 异步应为真,其他详细信息,,,

     $(function() {
        $("form").submit(function(e) {
            e.preventDefault();
            var formData = new FormData($(this));
            $.ajax({
                url: '/formfill',
                type: 'POST',
                data: formData,
                async: true,
                cache: false,
                contentType: false,
                processData: false,
                success: function(response) {
                    console.log(response);
                }
            });
        })
    });

here is my test code on localhost,that works fine: 这是我在localhost上的测试代码,可以正常工作:

<!DOCTYPE html>
<html>

<head>
    <title>d</title>
    <style></style>
    <meta charset="UTF-8">
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
</head>

<body>
    <form action="http://localhost:800/github/test/formfill.txt" method="POST" , enctype="application/x-www-form-urlencoded">
        <input class="formfill" type="text" name="name" placeholder="Your name">
        <br>
        <input class="formfill" type="text" name="mailId" placeholder="Your email">
        <br>
        <input id="submit-button" class="formfill sumbit-button" type="submit" value="Submit">
    </form>
    <script>
    $(function() {
        $("form").submit(function(e) {
            e.preventDefault();
            var formData = new FormData($(this));
            $.ajax({
                url: 'http://localhost:800/github/test/formfill.txt',
                type: 'POST',
                data: formData,
                async: true,
                cache: false,
                contentType: false,
                processData: false,
                success: function(response) {
                    console.log(response);
                }
            });
        })
    });
    </script>
</body>

</html>

Your BE is good but you will need to update the client code. 您的BE很好,但是您需要更新客户端代码。

You should use Ajax to accomplish this task. 您应该使用Ajax完成此任务。 Ajax will send an HTTP request via the web API and won't trigger the browsers redirect action (which submit and anchor tag triggers). Ajax将通过Web API发送HTTP请求,并且不会触发浏览器重定向操作(提交和定位标记触发器)。 And I see you are using jQuery so you have see http://api.jquery.com/jquery.ajax/ or https://api.jquery.com/jquery.post/ . 而且我看到您正在使用jQuery,所以您看到了http://api.jquery.com/jquery.ajax/https://api.jquery.com/jquery.post/

The thing is that you will need to get the form data manually (via javascript). 事实是,您将需要手动获取表单数据(通过javascript)。 You can use jQuery as well https://api.jquery.com/serializeArray/ . 您也可以使用jQuery https://api.jquery.com/serializeArray/

jQuery docmintation is really good. jQuery docmintation真的很好。 you should give it a look. 你应该看看。

Hope this will help you solve your issue. 希望这可以帮助您解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM