0
我試圖做一個主頁面('GET /'時呈現的視圖),其中有一個表單提交一個字段與POST提交(' /'),那麼'路由'將從控制器調用一個函數來檢查數據庫,如果該值已經在數據庫中,我會在主頁面上顯示一些錯誤消息。Sails.js呈現的'視圖'和控制器之間的交互
可以這樣做嗎?
我唯一使用的方法是根據查詢結果使用'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發佈是否安全。
我可以使用ajax工作,只關心這個方法的安全性。 – Devgom
我也會關心未加密的郵件。有許多方法可以在Sails中實現將HTTP請求轉換爲HTTPS請求的策略。很高興看到。 – Royalist