Node.js使用Express和EJS更新视图中的单个元素

时间:2016-09-27 19:36:18

标签: javascript node.js express ejs

我需要更改服务器端的value2并刷新视图,所以问题是:

如何更新和刷新视图,但只能使用新的value2

服务器:

var express = require("express");
var app =  express();
app.set('view engine', 'ejs');
app.set('view cache', false);

app.set('title', 'Test');

var bodyParser=require("body-parser"); 

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

app.use(express.static('public'));

app.get('/', function( req, res, next ) {
    res.render('test', { value1: 'A', value2: 'B', value3: 'C', value4: 'D' } );
});

app.post('/', function( req, res, next ) {
// I don't know value1, value3 and value4 :(
// and the Next line doesn't work
  res.render('test', { value2: 'X' } );
});

app.listen(3001);

客户端:

<!DOCTYPE html>
<html>
<head>
    <title> Hi </title>
</head>
<body>
    <form id="update" method="post" action="/" >
        <h2> This is Value1 (<%= value1 %>) and This is Value2 (<%= value2 %>) </h2>
        <h2> This is Value3 (<%= value3 %>) and This is Value4 (<%= value4 %>) </h2>
        <button type="submit" >Change Value2</button>
    </form>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

您可能希望使用隐藏的输入元素(<input type="hidden">)。所以你的HTML将是

<!DOCTYPE html>
<html>
<head>
    <title> Hi </title>
</head>
<body>
    <form id="update" method="post" action="/" >
        <input type="hidden" name="value1" value="<%= value1 %>">
        <input type="hidden" name="value2" value="<%= value2 %>">
        <input type="hidden" name="value3" value="<%= value3 %>">
        <input type="hidden" name="value4" value="<%= value4 %>">
        <h2> This is Value1 (<%= value1 %>) and This is Value2 (<%= value2 %>) </h2>
        <h2> This is Value3 (<%= value3 %>) and This is Value4 (<%= value4 %>) </h2>
        <button type="submit" >Change Value2</button>
    </form>
</body>
</html>

您需要按照以下

更新req.post路线
app.post('/', function( req, res, next ) {
  res.render('test', { value1: req.body.value1, value2: 'X', value3: req.body.value3, value4: req.body.value4 } );
});