Express.js-在同一页面上发送警报作为响应

Express.js - Send an alert as a response while staying on same page

本文关键字:响应 js- 一页 Express      更新时间:2023-09-26

我在一个视图中有3个表单,当提交时,会在mysql数据库中添加新条目。每当添加条目时,我都会发送一条警告,说"您已成功添加X",而无需从页面导航。

// Form to be Submitted
<form method="post" action="route/action/">
    <input type="text" name="name">
</form>

// Route
exports.action = function (req, res) {
    client.query();
    // What kind of response to send?
}

如何发送警报?我应该发送什么样的回复?

谢谢!

您需要做的是向您的express服务器发出ajax请求,并评估响应并相应地提醒用户。这个客户端部分和其他编程语言一样。

例如。在jquery客户端部分,您可以执行此

$.ajax({
 url: 'route/action/',
 type: "POST",
 data: 'your form data',
 success: function(response){
  alert('evaluate response and show alert');
 }
}); 

在你的epxress应用程序中,你可以有这样的

app.post('route/action', function(req, res){
  //process request here and do your db queries
  //then send response. may be json response
  res.json({success: true});
});