我使用Ajax和Node JS让用户在一个页面的应用程序上注册。当用户点击注册时,我将其设置为检查用户名是否被占用。到目前为止,这一切都有效。但是,现在我需要提醒用户他们的用户名已被删除。如何以这种方式打印错误或将错误闪现给用户?问题是我在避免页面刷新。
app.post("/quiz", function(req, res, next){
User.findOne({username: req.body.username}, function(err, user){
if(err) { console.log(err)}
if(user) {
console.log(user)
// I NEED TO SEND THE ERROR HERE SAYING THE USERNAME IS TAKEN
// I NEED TO SEND THE ERROR HERE SAYING THE USERNAME IS TAKEN
// I NEED TO SEND THE ERROR HERE SAYING THE USERNAME IS TAKEN
}
});
//continue with your registration logic
var newUser = new User({username: req.body.username, datapoint: req.body.datapoint});
User.register(newUser, req.body.password, function(err, user){
// if(res.error){
if(err){
req.flash("error", err.message);
res.redirect('back')
return res.render("quiz");
} else {
passport.authenticate("local")(req, res, function(){
// req.flash("success", "Welcome to JobQuiz " + user.username);
res.redirect("jobquiz");
console.log(req.body.datapoint)
});
}
});
});
Ajax设置
$(function() {
$("#checkpaymentForm").on("submit", function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: 'POST',
data: $(this).serialize(),
dataType:'json',
})
});
});
答案 0 :(得分:2)
首先在服务器代码的if语句中发送您的响应:
app.post("/quiz", function(req, res, next){
User.findOne({username: req.body.username}, function(err, user){
if(err) { console.log(err)}
if(user) {
res.json({"message": "false" });
}
});
然后在你的前端添加成功函数来处理响应:
$(function() {
$("#checkpaymentForm").on("submit", function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: 'POST',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
if (data.message === "false") {
//TODO: alert users here
}
})
});
});