【问题标题】:To submit a form without redirecting to other page提交表单而不重定向到其他页面
【发布时间】:2018-07-13 17:11:52
【问题描述】:

我一直在尝试制作一个在线 HTML 表单,它可以提交表单并将数据发布到本地数据库。但是,我不希望页面被重定向到/formfill URL 并将数据发送到数据库而不重定向页面。我已经尝试了很多。然而,没有运气。 这是我的后端 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");
});

这是我的 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>

这是我的 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>

使用 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>

我想要做的就是提交表单而不被重定向到/formfill 或刷新页面。

【问题讨论】:

  • 简答:做一个 AJAX 请求。
  • 是的,我一直想这样做,在每个这样的帖子上都说执行 ajax。但它不起作用,它仍然被重定向到 '/formfill' 并显示在 json 中的表单数据
  • 如果共识是使用 AJAX 并且它不起作用,那么您为什么没有将它包含在 this 问题中?我们在这里帮助您自助!
  • 是的,我错了,正在编辑帖子。
  • submit 处理程序应该在表单上,​​而不是提交按钮上。

标签: javascript jquery html node.js forms


【解决方案1】:

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

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>

【讨论】:

    【解决方案2】:

    async 应该是 true 和其他细节,,,

         $(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);
                    }
                });
            })
        });
    

    这是我在 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>
    

    【讨论】:

    • @AlpitAnand “不工作”是什么意思?浏览器控制台中的任何错误。这看起来应该没问题。
    • jquery-3.2.1.min.js 加载资源失败:服务器响应状态为 400 (Bad Request)
    • 我正在调查它,它是我的控制台日志
    • 仍被重定向到表单填写。 :-(
    • @AlpitAnand "jquery-3.2.1.min.js 加载资源失败:服务器响应状态为 400 (Bad Request)",存在与提交无关的问题表单,可能是 HTTP 使用不当,将 URL 复制粘贴到地址栏中然后调试。
    【解决方案3】:

    您的 BE 不错,但您需要更新客户端代码。

    您应该使用 Ajax 来完成这项任务。 Ajax 将通过 web API 发送 HTTP 请求,并且不会触发浏览器重定向操作(提交和锚标记触发)。 我看到你正在使用 jQuery,所以你看到了 http://api.jquery.com/jquery.ajax/https://api.jquery.com/jquery.post/

    问题是您需要手动(通过 javascript)获取表单数据。你也可以使用 jQuery https://api.jquery.com/serializeArray/.

    jQuery 文档真的很棒。你应该看看。

    希望这能帮助您解决问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-24
      • 2014-10-09
      • 2020-02-18
      • 2014-06-11
      • 2015-05-14
      • 2015-10-11
      相关资源
      最近更新 更多