gpt4 book ai didi

javascript - Node.js 使用 Express 和 EJS 更新 View 中的单个元素

转载 作者:太空宇宙 更新时间:2023-11-04 02:46:44 26 4
gpt4 key购买 nike

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

如何更新和刷新 View ,但只能使用新的 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>

最佳答案

您可能喜欢使用隐藏的输入元素( <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 } );
});

关于javascript - Node.js 使用 Express 和 EJS 更新 View 中的单个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39732955/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com