Javascript 向节点服务器发送邮件
我正在努力学习,我遇到了一个问题。我有一个表单可以向MongoDB提交商品名称、价格和图片。在我的节点路由中,我使用res.json作为响应。使用jQueryPost方法时,我可以停留在页面上,将数据返回到控制台或变量或其他任何地方。当我更改为angular POST方法时,实际上我将进入一个包含JSON响应的新页面。这当然不是我想要的。我想在不离开页面的情况下更新数据库,获取新数据,并更新模型 这是我的节点路由。Javascript 向节点服务器发送邮件,javascript,node.js,angularjs,mongodb,Javascript,Node.js,Angularjs,Mongodb,我正在努力学习,我遇到了一个问题。我有一个表单可以向MongoDB提交商品名称、价格和图片。在我的节点路由中,我使用res.json作为响应。使用jQueryPost方法时,我可以停留在页面上,将数据返回到控制台或变量或其他任何地方。当我更改为angular POST方法时,实际上我将进入一个包含JSON响应的新页面。这当然不是我想要的。我想在不离开页面的情况下更新数据库,获取新数据,并更新模型 这是我的节点路由。 router.post('/items/add', function(req,
router.post('/items/add', function(req, res){
// handle image upload
fs.readFile(req.files.image.path, function (err, data) {
var imageName = req.files.image.name
/// If there's an error
if(!imageName){
console.log("There was an error")
res.redirect("/");
res.end();
} else {
var newPath = '/uploads/' + imageName;
/// write file to uploads/fullsize folder
fs.writeFile(newPath, data, function (err) {
});
}
});
// save info to database
var newItem = new Item({
name : req.param('Name'),
price : req.param('Price'),
image : req.files.image.name
});
newItem.save(function(err){
if(err){
console.log(err);
} else{
Item.find(function(err, items){
if (err){
return console.log(err);
} else{
res.json({
items : items
});
}
});
}
});
});
这是我的角度代码:
var allItems = angular.module('allItems', []);
allItems.controller('allItemsCtrl', function ($scope, $http) {
$scope.updateItems = function(){
$http.get('/allItems').success(function(data){
$scope.theitems = data.allItems;
});
};
// The culprit
$scope.postItems = function(){
$scope.formData = {};
$http.post('/items/add', formData).success(function(data){
$scope.theitems = data.allItems;
});
};
$scope.updateItems();
});
数据发布正确,但是我希望它像一篇AJAX文章一样,而不是离开页面。当你有一个真正的HTML表单,上面有一个像这样的提交按钮时,我该如何实现这一点呢
<form method="post" action="http://yoursite.com/items">
<input type="text"/>
<button type="submit">Submit</button>
</form>
<form ng-submit="postItems()">
<input type="text"/>
<button type="submit">Submit</button>
</form>
提交
然后,它将进行页面刷新,而不管您最终在JavaScript中做了什么。我会保留HTML表单元素,使其语义正确,但不需要方法或动作属性。相反,在你的表单上使用
<form method="post" action="http://yoursite.com/items">
<input type="text"/>
<button type="submit">Submit</button>
</form>
<form ng-submit="postItems()">
<input type="text"/>
<button type="submit">Submit</button>
</form>
提交
真正的问题是您究竟是如何设法使一个角度$http.post()
请求的行为不像AJAX请求!如何调用$scope.positems()
?哈!哈哈哈哈@ExpertSystems我在使用ng submit,但我一定是做错了什么,因为你是对的,它应该可以工作。