POST请求后如何刷新表单页面? [英] How to refresh form page after POST request?

查看:110
本文介绍了POST请求后如何刷新表单页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm working on a single page website using Netbeans (HTML5 with Node.js and Express JS). The following is a sample of what I need to do (Not the real website).

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

I have a form, when I click submit, I need it to post data to DB and refresh the current page that has the form. Right now it posts the data to DB and displays blank page (looks like empty JSON formatted page. The reason I need to refresh is I'm creating REST APIs to display data from the same DB on the same page (index.pug).

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

In my case I'm using Jage/Pug instead of HTML files

//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

and here is 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中这样做:

I tried doing this in jQuery:

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

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

It works but only when I click on ADD button without having any values in the input fields.

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

Is it possible to reload the page after a POST request? Is there anything I'm doing wrong here?

先谢谢您!

推荐答案

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

In addition to form-submit which gives away connection and empty browser DOM. In addition to that you are using res.send() which just send away data to browser and since there's no JavaScript in DOM to take care of response and response is displayed with no HTML.

要在html render中显示结果,另一个在ejs中显示响应数据.

To show result in html render an other ejs with response data.

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

Better Approach single-page application using javaScript I don't understand pug/jade so will use 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等.

The reason you are seeing empty page with json is you are using form submit which is not a single page application method. In order to stick to same page and just change html content use any JavaScript framework for UI like AngularJs, reactJs, backboneJs etc.

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

You can also use AJAX call to submit data and stay on same page and display your response from API in same HTML by hiding and displaying different HTML tags.

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

I have given similar answers in different posts too check all these out:

  1. 如何通过ajax请求时渲染HTML页面形式的nodejs-api
  2. 如何使用表达框架从节点js请求中获取字段
  3. how-to-render-a -html-page-form-nodejs-api
  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

这篇关于POST请求后如何刷新表单页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆