[英]ajax request posting undefined data from form in nodejs
I am trying to make a comment form which adds a comment in array of blog schema but when I am using ajax it is giving undefined below the places where I have console log and when I am using simple post request it is working fine. 我正在尝试创建一个注释表单,以在博客架构数组中添加注释,但是当我使用ajax时,它在控制台日志的位置下方给出了undefined,而当我使用简单的发布请求时,它可以正常工作。 I am using mongoose, nodejs , express, jquery ajax my script is as follows
我正在使用mongoose,nodejs,express,jquery ajax我的脚本如下
var frm = $('#commentForm');
frm.submit(function (e) {
e.preventDefault();
console.log('clicked');
$.ajax({
type: 'POST',
url: "/blog/addComment",
contentType: "application/json; charset=utf-8",
dataType: 'json'
})
.done(function(data) {
addNewComment(data);
})
.fail(function() {
console.log("Ajax failed to fetch data");
});
});
function addNewComment(data){
console.log(data);
}
my routes is as follows 我的路线如下
//add comments
router.post('/addComment',function(req,res,next){
console.log(req.body.comment+" "+ req.body.userId+" "+req.body.postId);
var newComment = {
'text': req.body.comment,
'author': req.body.userId
}
Post.addComment(req.body.postId, newComment, function(err,comment){
if(err) throw err;
console.log(comment);
res.send(comment);
});
});
and my mongoose schema is 我的猫鼬模式是
//add comments
module.exports.addComment = function( postId, newComment, callback){
var query = { '_id': postId};
console.log('postid: '+postId+" newcomment: "+newComment.text+ " "+newComment.author);
Post.findOneAndUpdate( query, { $push:{'comments': newComment} }, {new:true} , callback);
}
That's because data is not defined in ajax call , use following provide the frm is the actallu form or use use data : form name.serialize() 那是因为数据没有在ajax调用中定义,请使用以下命令(如果frm是actallu形式)或使用use数据:形式name.serialize()
var frm = $('#commentForm');
frm.submit(function (e) {
e.preventDefault();
console.log('clicked');
$.ajax({
data : $(this).serialize(),
type: 'POST',
url: "/blog/addComment",
contentType: "application/json; charset=utf-8",
dataType: 'json'
})
.done(function(data) {
addNewComment(data);
})
.fail(function() {
console.log("Ajax failed to fetch data");
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.