我在 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/