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

Pass data from Jade view to controller

本文关键字:控制器 视图 数据 Jade      更新时间:2023-09-26

我有一个翡翠的提交按钮(下面的代码):

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

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

从客户端到服务器的通信需要 ajax,假设您不希望重新加载页面。 将按钮更改为如下所示:

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

要使用 jquery 的 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阅读该"消息"。