将数据从Jade视图传递到控制器

时间:2016-02-07 09:49:33

标签: javascript node.js express pug

我在jade中有一个提交按钮(下面的代码):

p
    a(href='/commands/new')
    button.btn.btn-primary(type='submit')
        i.glyphicon.glyphicon-plus
        |           Add commands

调用控制器代码:

router.get('/new', function(req, res) {    
    console.log("inside commands.js controller");
    // custom biz logic here...
    // need to get the value of the key passed to the controller when someone hits the "Add commands" button above
});

我想在按下添加命令按钮时将一些数据传递给控制器​​。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

从客户端到服务器的通讯需要ajax,前提是您不希望重新加载页面。更改按钮,使其看起来像这样:

button.btn.btn-primary(onclick='sendMessage()')

要使用jquery's ajax向该控制器发送消息,请将其添加到您的模板中:

script.
  function sendMessage(){
    var xhr = $.ajax({
      "url": "/new?message=" + "(insert your message to the server here)",
      "method": "get"
    });

    xhr.done(function(data){
      // this runs when the request was successful and data is what the server sends back
    });

    xhr.fail(function(jqXhr, error){
      // this runs if the request failed
    });
  }

然后,您可以在服务器上使用req.query.message阅读该“消息”。