我有一张表格:
<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');
}
});
});
一切功能都有效,我只想知道如果用户已成功注册,我将如何显示消息。我还想知道这是否是处理表格的正确方法。
答案 0 :(得分:0)
签署后处理成功状态。
success: function(user) {
// Hooray! Let them use the app now.
res.redirect('/#register');
}
成功注册后,您将重定向到/ #register页面。您可以在加载此页面时显示警报。
答案 1 :(得分:0)
前端JS:
我们不会以通常的方式提交表单,而是使用jQuery-AJAX来实现此目的:
使用网页jQuery
标记中的以下<script>
标记将<head>
附加到您的网页:
<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('/', function(req, res) { ... user.signUp(null, { success: function(user) { res.send(your_success_message); // send your success message or status or result object using this method, it will call the success function of your ajax object on the front-end }, error: function(user, error) { res.send(your_error_message); // similarly send the error message, or status, or object. } }); });