【问题标题】:Pass data from Jade view to controller将数据从 Jade 视图传递到控制器
【发布时间】:2016-02-07 09:49:32
【问题描述】:

我在翡翠中有一个提交按钮(代码如下):

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
});

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

【问题讨论】:

  • 你有没有想过这个问题?

标签: javascript node.js express pug


【解决方案1】:

假设您不想重新加载页面,那么从客户端到服务器的通信需要 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 阅读该“消息”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 2017-11-30
    • 2011-09-09
    • 1970-01-01
    相关资源
    最近更新 更多