在我的个人页面(1 页网站)的底部,我有一个联系表单,可以将消息发送到我的数据库,以便我稍后阅读。
问题是,如果我不重定向到任何地方,页面就不会重新加载,这正是我想要的,但正在搜索某些内容并在选项卡中显示加载图标,最终断开连接并显示来自 Cloud9 的“ECONNRESET”错误。
如果我确实重定向回/#contact(到页面,然后向下到联系部分),那么它会重新加载页面,但由于网站的功能,这不是我想要发生的情况。它有一些动画在发送消息后立即加载,然后重新加载将它们取消,看起来很糟糕。
如何才能使页面在发送消息后不必重新加载,这意味着我不必重定向到任何地方,但也不会收到 ECONNRESET 错误?
app.post("/", function (req, res){
// Retrieve form data
var name = req.body.name;
var email = req.body.email;
var subject = req.body.subject;
var message = req.body.message;
var newMessage = {name: name, email: email, subject: subject, message: message};
// Save new message to database
Message.create(newMessage, function (err, sendMessage) {
if (err) {
console.log(err);
} else {
console.log(sendMessage);
}
});
});
最佳答案
如果您不通过 AJAX 发布表单,则应重定向到呈现 View 的 GET
端点。如果您不想重定向,那么至少您需要调用 res.render() 来呈现正确的 View 。不重定向的缺点是,如果用户刷新页面,可能会提示他们重新提交表单。
Message.create(newMessage, function(err, sendMessage){
if(err){
console.log(err);
} else {
console.log(sendMessage);
res.render('contact'); //change 'contact' to the name of the view you are rendering
}
});
关于javascript - 表单提交后是否重定向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49220412/