我正在尝试使用AJAX和JQuery重构我的代码,并且在第一个障碍时已经失败了!
基本上我正在做的是一个博客,最初我添加了一个评论部分,通过在添加新评论时重定向到“显示”页面。 这没关系,但我真的想使用AJAX和JQuery将它重构为一个1页的进程,特别是因为我现在想要添加一个编辑注释的函数,我不希望将用户重定向到另一个表单。
这是添加新评论的表单代码:
Add comment
Submit
这是我的POST路线:
router.post("/", middleware.isLoggedIn, function(req, res){
// lookup blog using id
Blog.findById(req.params.id, function(err, blog){
if(err) {
console.log(err);
res.redirect("/blogs");
} else {
// create new comment
Comment.create(req.body.comment, function(err, comment){
if(err) {
req.flash("error", "Something went wrong");
console.log(err);
} else {
if(req.xhr){
res.json(comment);
} else {
}
comment.author.id = req.user._id;
comment.author.username = req.user.username;
comment.author.image = req.user.image;
comment.save();
// connect new comment to campground
blog.comments.push(comment);
blog.save();
// redirect to campground show page
req.flash("success", "Successfully added comment");
res.redirect("/blogs/" + blog._id);
}
});
}
});
});
这是我的AJAX代码:
$('#newComment').submit(function(e){
e.preventDefault();
var formData = $(this).serialize();
$.post("/", formData, function(data){
console.log(data);
});
});
当我深入研究试图运行代码的Chrom开发工具时,我得到的是以下错误:
// Do send the request (this may raise an exception)
xhr.send( options.hasContent && options.data || null );
} catch ( e ) {
我试过从其他用户的问题中调查这个问题但是我刚刚开始学习AJAX而且我已经陷入了第一个障碍,其中很多对我来说都没有意义!
这是运行代码时的chrome日志: