如何在节点中为用户创建某种警报

How can I create some kind of alert for the user in node?

本文关键字:创建 用户 节点      更新时间:2023-09-26

我有一个表单:

<form class="form-inline" action="/" method="post">
    <div class="form-group">
        <label class="sr-only">Username</label>
        <input name="username" type="text" class="form-control" placeholder="Desired Username">
    </div>
    <br>
    <br>
    <div class="form-group">
        <label class="sr-only" for="exampleInputEmail3">Email address</label>
        <input name="email" type="email" class="form-control" id="exampleInputEmail3" placeholder="Email">
    </div>
    <br>
    <br>
    <div class="form-group">
        <label class="sr-only" for="exampleInputPassword3">Password</label>
        <input name="password" type="password" class="form-control" id="exampleInputPassword3" placeholder="Password">
    </div>
    <br>
    <br>
    <button type="submit" class="btn btn-default">Register</button>
</form>

这是我的app.js:

app.post('/', function(req, res) {
  var user = new Parse.User();
  user.set("username", req.body.username);
  user.set("password", req.body.password);
  user.set("email", req.body.email);
  user.signUp(null, {
    success: function(user) {
      // Hooray! Let them use the app now.
      console.log(user);
      res.redirect('/#register');
    },
    error: function(user, error) {
      // Show the error message somewhere and let the user try again.
      console.log(error.message);
      res.redirect('/#register');
    }
  });
});

一切功能正常,我只想知道如果用户是否成功注册,我如何显示消息。我还想知道这是否是处理表单的正确方法。

处理注册后的成功状态。

success: function(user) {
  // Hooray! Let them use the app now.
  res.redirect('/#register');
}

成功注册后,您将重定向到/#注册页面。加载此页面时,您可以显示警报。

前端JS:

我们将使用jQueryAJAX来实现此目的,而不是以通常的方式提交表单:


使用网页<head>标签中的以下<script>标签将jQuery附加到网页:

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>

在相同的<head>中使用以下内容进行跟进:

<script type="text/javascript">
$('.form-inline').submit(function(event) {
  $.ajax({
    type: "POST", // the request type
    url: "/", // the URL where your form data will be sent
    data: $(this).serialize(), // the form data to be sent
    success: function(data) { // this function will be called when you do a res.send from the back-end
        alert(data); // although I would suggest you use a modal or some other solution to display your success message
        window.location.href = your_redirect_url; // this will redirect the user to your /#register url
    }
  });
  event.preventDefault(); // to prevent the form from being submitted the usual way
});
</script>

注意:这只是一个帮助您入门的示例。


后端JS:

app.post('/',函数(req,res){。。。user.signUp(null{成功:功能(用户){res.send(您的成功消息);//使用此方法发送成功消息或状态或结果对象,它将在前端调用ajax对象的成功函数},error:函数(用户,错误){res.send(your_error_message);//类似地发送错误消息、状态或对象。}});});