javascript - 将数据从 Jade View 传递到 Controller

标签 javascript node.js express pug

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

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

调用 Controller 代码:

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

我想在按下添加命令按钮时将一些数据传递到 Controller 。我怎样才能实现这个目标?

最佳答案

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

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

使用 jquery's ajax 向该 Controller 发送消息将其添加到您的模板中:

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 读取该“消息”。

关于javascript - 将数据从 Jade View 传递到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35251982/

相关文章:

callback - 如何处理回调函数中的响应(以 nodejs 中的 cradle 为例)

javascript - 我可以在 app.get 中使用不同路径的 app.use

javascript - 为什么当我更改状态时整页更新?

node.js - net::ERR_CONNECTION_CLOSED 在 mongo 文档中有超过 7 个子文档时在远程服务器上

node.js - Firebase 数据库AuthVariableOverride 不起作用

node.js - 如何在ubuntu上安装node-xmpp

node.js - 在nodejs中执行sql查询时返回未定义的值

javascript - AngularJs 的 $watch 函数 - 没有返回?

javascript - 在 React 状态中保持更新的对象关系

javascript - 输入错误 : cannot type 'S' into search input