Sails.js 渲染的 'view' 和控制器之间的交互

Sails.js interaction between the rendered 'view' and the controller

我正在尝试制作一个主页('GET /' 时呈现的视图),其中有一个带有一个字段的表单,该字段使用 POST 提交到 ('/') 然后 'routes' 将从控制器调用一个函数来检查数据库,如果该值已经在数据库中,我将在主页上显示一些错误消息。

这可以做到吗?

我使用的唯一方法是根据查询结果使用 'res.redirect()' 或 'res.view()' 的方法,但我尽量不再次呈现主页,也不更改 url.

感谢您的宝贵时间。

编辑 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 到 post 是否安全。

是的,可以做到。

让您的表单在提交时触发 Javascript 方法。 JQuery 就可以了:

$.ajax({
  type: "POST",
  url: 'your/api/route/',
  data: {
      value: 'to server'
  },
  success: function(response) {
      /* Handle Response */
  }
});

然后,您将需要 setup the route 来处理 POST,并包含 jQuery 或另一个支持 AJAX 的 Javascript 库.最后,在您与路由关联的方法中,执行您需要对数据库执行的任何操作。