[英]Node.js With Express And EJS updating a single element in view
What I need is to change value2
on the server side and refresh the view, so the question is: 我需要在服务器端更改
value2
并刷新视图,所以问题是:
How can I update and refresh the view but only with the new value2
? 如何仅使用新的
value2
更新和刷新视图?
Server: 服务器:
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);
Client: 客户:
<!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>
You may like to use hidden input element( <input type="hidden">
). 您可能想使用隐藏的输入元素(
<input type="hidden">
)。 So your html would be 所以你的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>
and you need to update your req.post
route as following 并且您需要按以下方式更新
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 } );
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.