将确认警报从Node/Express发送到浏览器,而无需重新加载页面

Sending confirmation alerts from Node/Express to Browser without reloading page

本文关键字:新加载 加载 浏览器 确认 Node Express      更新时间:2023-09-26

我有一个带工作用户身份验证系统的web应用程序。当用户更新他们的数据(例如电子邮件地址或密码)时,它会向服务器发送POST请求,服务器反过来更新数据库。我想在成功或错误时在现有页面上有一个引导程序风格的块警报闪烁。我可以通过(1)来自服务器的res.send响应和(2)监视res.send数据并将块警报HTML代码插入浏览器的jQuery脚本的组合来实现这一点吗?

app.post块(通过post请求接收更新的用户数据)看起来像这样:

app.post('/updateuser', function(req, res) {
console.log(req.body);
[code here to update database]
res.send('[code to send to jQuery here]');

呈现块警报的HTML是:

<div class="alert alert-success">
    <button type="button" class="close" data-dismiss="alert">×</button>
    <strong>Success!</strong>User data has been updated.
</div>

如果这是可能的,(a)服务器端res.send或类似代码和(b)客户端jQuery代码会是什么样子?

提前感谢!

您想要的是连接闪存:https://github.com/jaredhanson/connect-flash

参见示例https://github.com/jaredhanson/connect-flash/blob/master/examples/express3/views/index.ejs以在渲染的模板中显示flash,或者如果需要,使用消息发出警报。