【发布时间】:2017-04-26 09:57:44
【问题描述】:
我正在尝试制作一个主页(在“GET /”时呈现的视图),其中有一个带有一个字段的表单,该表单通过 POST 提交到(“/”)然后“路由”将调用一个函数将检查数据库的控制器,如果该值已经在数据库中,我将在主页上显示一些错误消息。
这个可以吗?
我使用的唯一方法是根据查询结果使用“res.redirect()”或“res.view()”,但我试图不呈现主页再次也不更改网址。
感谢您的宝贵时间。
编辑 1:尝试@Royalist 答案
编辑 2:开始学习一点 jQuery,改变了一些东西
编辑 3:控制器正在做它应该做的事情
编辑 4:现在一切正常!
路线
'GET /thing': {
controller: 'ThingController',
action: 'getThing'
},
'POST /thing': {
controller: 'ThingController',
action: 'postThing'
},
控制器
getThing: function (req, res) {
res.view('thing');
},
postThing: function (req, res) {
console.log('Inside postThing');
Thing.findOne({name: req.param('name')}).exec(function (err, thing) {
if (err) {
return res.json({status: 3});/* Some nasty error */
}
if (!thing) {
Thing.create({name: req.param('name')}).exec(function (err, createdThing) {
if (err) {
console.log('Wrong data');
return res.json({status: 2});/* The data is not correct */
}
console.log('Everything ok');
return res.json({status: 0});/* Created succesfully */
});
}
if (thing) {
console.log('Already exists');
return res.json({status: 1});/* The thing already exists */
}
});
}
查看
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function postThing(){
$.ajax({
url: '/thing',
method: 'POST',
data: {name: $("#name").val()},
success: function(res) {
switch (res.status){
case 0: {
console.log('Created succesfully!');
break;
}
case 1: {
console.log('This thing already exists');
break;
}
case 2: {
console.log('What you are trying to insert is wrong');
break;
}
case 3: {
console.log('Boooom');
break;
}
}
}
});
}
</script>
</head>
<body>
<form action="Javascript:postThing();" method="POST" id="form">
<input type="text" name="name" id="name" />
<button>Submit</button>
</form>
</body>
现在一切正常。
我唯一关心的就是安全问题。不知道用ajax发帖安全不安全。
【问题讨论】:
标签: controller routes sails.js