我通过ajax向服务器发送帖子请求:
result.ejs
$.ajax({
type: "POST",
url: "/result",
data: { score: score, rank: rank, name: name, email: email, historyLog: historyLog }
});
我正在重温它并将数据保存到数据库中:
resultController.js
app.post('/result', urlencodedParser, function(req, res) {
var user = new User({
name: req.body.name,
email: req.body.email,
score: req.body.score,
rank: req.body.rank,
historyLog: req.body.historyLog
});
user.save(function(err) {
if (err) throw err;
console.log('User saved successfully!');
});
});
保存后我想渲染一个新视图,但我无法正常工作。 我尝试在保存功能之后添加它:
res.redirect('page')
,res.render('page')
,设置标题html / text
以上都不起作用。有什么建议吗?
答案 0 :(得分:2)
AJAX通常用于不想要在其他地方导航,而是在后台与服务器通信。要按照自己的方式进行操作,请在res.send("done");
之后立即使用保存回调中的console.log('User saved successfully!);
,然后将其添加到您的ajax请求中:
success: function () { window.location.href = "/page"; }
实现整个过程的一种更简单的方法是使用<form method="post" action="/result">
并提交它。
答案 1 :(得分:0)
这样可以发布。 更好地使用表格发布。
app.post('/result', function(req, res) {
new user({
name: req.body.name,
email: req.body.email,
score: req.body.score,
rank: req.body.rank,
historyLog: req.body.historyLog
}).save(function(err,doc) {
if (err) throw err;
else { res.render('pagename.ejs'); }
console.log('User saved successfully!',doc);
}); });
希望这会对你有所帮助。
答案 2 :(得分:-2)
如果你想在保存后呈现页面 - 将其添加到保存回调中,就像这样
app.post('/result', urlencodedParser, function(req, res) {
var user = new User({
name: req.body.name,
email: req.body.email,
score: req.body.score,
rank: req.body.rank,
historyLog: req.body.historyLog
});
user.save(function(err) {
if (err) throw err;
console.log('User saved successfully!');
res.render('page');//ADD HERE redirect o render
});
});