POST请求后如何刷新表单页面?

时间:2018-08-31 21:15:55

标签: javascript jquery html node.js express

我正在使用Netbeans(带有Node.js和Express JS的HTML5)在单页网站上工作。以下是我需要做的示例(不是真正的网站)。

我有一个表单,当我单击“提交”时,我需要它来将数据发布到DB并刷新具有该表单的当前页面。现在,它会将数据发布到数据库并显示空白页面(看起来像是空的JSON格式的页面。我需要刷新的原因是我正在创建REST API,以在同一页面(index.pug)上显示来自同一数据库的数据。

就我而言,我使用的是Jage / Pug而不是HTML文件

//index.pug
form(method='post', class="form-signin")
    input(type='text',class="form-control", name='fname')
    input(type='text',class="form-control", name='lname')
    button#button(type='submit', value='Submit') ADD

这是app.js

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const bodyParser = require("body-parser");
const pg = require('pg');
const config = {
user: 'postgres',
database: 'postgres',
    password: 'password',
    port: 5432,
    idleTimeoutMillis: 30000// (30 seconds) how long a client is allowed to remain idle before connection being closed
};
const pool = new pg.Pool(config);

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(function(req, res, next){ //This is so I can use the pool in routes js files
        req.pool = pool;
        next();
    });

app.use('/', indexRouter);
app.use('/users', usersRouter);

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

// catch 404 and forward to error handler
app.use(function(req, res, next) {
   next(createError(404));
});


// error handler
app.use(function(err, req, res, next) {
   // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
 });

module.exports = app;

这是routes / index.js

var express = require('express');
var router = express.Router();
const bodyParser = require("body-parser");

router.use(bodyParser.urlencoded({extended: true}));
router.use(bodyParser.json());

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
    });
//post to database
router.post("/",function (req, res, next) {
    // Grab data from http request
    var pool = req.pool;
    const data = {fname: req.body.fname, lname: req.body.lname};

 pool.connect(function (err, client, done) {
       if (err) {
           console.log("Can not connect to the DB" + err);
           res.status(400).send(err);
           }
           client.query('INSERT INTO public.names(fname, lname) values($1, $2)', [data.fname.toUpperCase(), data.lname.toUpperCase()],
              function (err, result) {
                done();
                if (err) {
                    console.log(err);
                    res.status(400).send(err);
                }
                res.status(200).send(result.rows);
                //res.redirect(req.get('referer'));
           });
        });
    });
//Create an API display all
router.get("/api/all", function (req, res, next) {
    var pool = req.pool;

    pool.connect(function (err, client, done) {
       if (err) {
           console.log("Can not connect to the DB" + err);
           res.status(400).send(err);
       }
       client.query('SELECT * FROM public.names', function (err, result) {
            done();
            if (err) {
                console.log(err.stack);
                res.status(400).send(err);
            }
            res.status(200).send(result.rows);
       });
    });
  });

module.exports = router;

我尝试在jQuery中这样做:

$('#button').click(function() {
        location.reload(true);
    });

它有效,但仅当我单击ADD按钮且输入字段中没有任何值时才有效。

是否可以在POST请求后重新加载页面?我在这里做错什么了吗?

先谢谢您!

3 个答案:

答案 0 :(得分:0)

您是否尝试过将动作参数添加到表单中?

form(method='post', class="form-signin", action="/#")

答案 1 :(得分:0)

由于按钮的类型为submit,因此您不必使用Javascript处理重新加载,因为它是默认的表单提交事件行为。

答案 2 :(得分:0)

编辑:除了form-submit之外,它还放弃了连接并清空了浏览器DOM。除此之外,您正在使用res.send(),它只是将数据发送到浏览器,并且由于DOM中没有JavaScript来处理响应,因此响应没有HTML显示。

要在HTML render中用另一个ejs的结果显示响应数据。

router/index.js

//post to database
router.post("/",function (req, res, next) {
  // Grab data from http request
  var pool = req.pool;
  const data = {fname: req.body.fname, lname: req.body.lname};

 pool.connect(function (err, client, done) {
   if (err) {
       console.log("Can not connect to the DB" + err);

       // This is how to display data with html
       res.render('error', {err});
       }
       client.query('INSERT INTO public.names(fname, lname) values($1, $2)', [data.fname.toUpperCase(), data.lname.toUpperCase()],
          function (err, result) {
            done();
            if (err) {
                console.log(err);

                // This is how to display data with html
                res.render('error', {err});
            }

            // This is how to display data with html
            res.render('desplayData', result.rows);
       });
    });
});

error.ejs

    <!DOCTYPE html>
<html >
    <head>
        <meta charset="UTF-8">    
        <title>Error</title>
    </head>
    <body>
        <p><%=err%></p>
    </body>
</html>

displayData.ejs

    <!DOCTYPE html>
<html >
    <head>
        <meta charset="UTF-8">    
        <title>Display Data</title>
    </head>
    <body>
        <p><%=rows%></p>
    </body>
</html>

使用javaScript的更好的单页应用程序 我不了解pug/jade,因此会使用html

index.html

<!DOCTYPE html>
<html >
    <head>
        <meta charset="UTF-8">    
        <title>Index</title>
    </head>
    <body>
        <input id="fName" type="text">
        <input id="lName" type="text">
        <p onclick="addInfo()">Submit</p>
        <!-- No need for `form` as will use JavaScript for Single Page Application -->

        <!-- This p tag will display response -->
        <p id="response"></p>

        <!-- This p tag will display error -->
        <p id="error"></p>
        <script type="text/javascript" src="/js/jquery.min.js"></script>
        <script>
             function addInfo() {
                // JavaScript uses `id` to fetch value
                let fName               = $("#fName").val(),
                    lName               = $("#lName").val();

                $.ajax({
                    "url": "/addDetail",
                    "method": "POST",
                    "data": {fName, lName}
                })
                .then( result => {
                    // On success empty all the input fields.
                    $("#fName").val('');
                    $("#lName").val('');
                    // Message to notify success submition
                    alert("Successfully added user.");

                    let newHTML = `<span>` + result + `</span>`;

                    $("#response").html(newHTML);

                    return;
                })
                .catch( err => {
                    // Notify in case some error occured
                    alert("An error occured.");

                    let newHTML = `<span>` + result + `</span>`;

                    $("#error").html(newHTML);

                    return;
                });
            }
        </script>
    </body>
</html>

router/index.js

//post to database
router.post("/addDetail",function (req, res, next) {
    // Grab data from http request
    var pool = req.pool;
    const data = {fname: req.body.fname, lname: req.body.lname};

     pool.connect(function (err, client, done) {
         if (err) {
             console.log("Can not connect to the DB" + err);
             res.status(400).send(err);
         }
         client.query('INSERT INTO public.names(fname, lname) values($1, $2)', [data.fname.toUpperCase(), data.lname.toUpperCase()],
            function (err, result) {
                done();
                if (err) {
                    console.log(err);
                    res.status(400).send(err);
                 }
                 res.status(200).send(result.rows);
                 //res.redirect(req.get('referer'));
            });
       });
 });

看到json空页的原因是您使用的是form submit,它不是单页应用程序方法。为了停留在同一页面上并仅更改html内容,请为UI使用任何JavaScript框架,例如AngularJs,reactJs,belimberJs等。

您还可以使用AJAX调用来提交数据并停留在同一页面上,并通过隐藏和显示不同的HTML标签显示来自API的相同HTML响应。

我在不同的帖子中也给出了类似的答案,也请检查所有这些内容:

  1. how to send data to html page and how to use ajax for single page application
  2. how-to-render-a-html-page-form-nodejs-api-when-requested-via-ajax
  3. how-to-fetch-fields-from-request-in-node-js-using-express-framework
  4. how-to-render-a-html-page-form-nodejs-api