Sails.js呈现的视图之间的交互'和控制器

时间:2017-04-26 09:57:45

标签: controller routes sails.js

我试图创建一个主页面(在' GET /'时呈现的视图),其中有一个表单,其中一个字段通过POST提交到(' /& #39;)然后'路线'将从将检查数据库的控制器调用一个函数,如果该值已经存在于数据库中,我将在主页上显示一些错误消息。

可以这样做吗?

我使用过的唯一方法是使用&res; red.red()'或者' 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发布是否安全。

1 个答案:

答案 0 :(得分:1)

是的,可以做到。

让您的表单在提交时触发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库。最后,在您与路径关联的方法中,执行数据库所需的任何操作。

相关问题