我的网站有一个帖子标签功能: Tag functionallity。 看看这段代码,我用javascript抓取这些标签并将它们保存到标签数组中:
var formNewPost = $("#formNewPost");
formNewPost.on("submit", function (event) {
var tagElements = $("span.tag span");
var tags = [];
for (var i = 0; i < tagElements.length; i++) {
var text = document.querySelectorAll("span.tag span")[i].innerText;
text = text.trim();
tags.push(text);
}
});
现在我有了合适的数组,现在我想把它保存到我的mongoDB数据库中。我的节点js代码:
var title = req.body.title;
var tags = // I want that array from client side to be here
var type = req.body.type;
var body = req.body.body;
var author = req.body.author;
var newPost = {title, author, tags, type, body, author};
Post.create(newPost, function (err, newPost) {
if (err) {
req.flash('error', 'An error occurred, please try again.');
res.redirect('/posts/new');
} else {
req.flash('success', 'Post created successfully.');
res.redirect('/posts');
}
});
但我怎么能这样做? 我尝试了这段代码,但它根本不起作用:
tags.push(text);
$.ajax({
type: "POST",
url: '/posts',
data: { tags : tags },
success: function(data)
{
alert("success!");
}
});
然后使用express:
获取数据 var tags = req.body.tags; // AN ARRAY FROM JAVASCRIPT
但它根本不起作用,问题是什么?