Ajax和Node.js的简单按钮单击示例? [英] Simple button click example with Ajax and Node.js?
问题描述
我对Ajax和Node.js + Express都是陌生的.此时,我正在尝试弄清楚如何通过按钮与前端和后端进行通信.
I am new to both Ajax and Node.js + Express. At this point I am trying to figure out how to communicate with both the front and back end through buttons.
我在HTML页面上有一个按钮,我想用它来从后端调用函数并将文本输出到客户端.
I have a button on an HTML page which I would like to use to call a function from the backend and output text to the client.
这是我根据需要拼凑而成的东西,但我正在寻找一个有关如何完成此操作的示例.
Here is what I've pieced together for what I need but I am looking for an example on how this could be done.
这一切都发生在/page
index.hjs文件
<button class="btn btn-success" onclick="install()">Install</button>
// Client Side Ajax Script
<script>
$('button').click(function () {
$.post('/page', {data: 'blah'}, function (data) {
console.log(data);
});
}, 'json');
</script>
app.js文件
app.post('/page', function (req, res, next) {
calling.aFunction();
res.write('A message!');
});
这些都是我需要的所有部分吗?需要进行哪些编辑才能使此功能正常工作?
Are these all the parts that I need and what needs to be edited to get this functionality to work?
推荐答案
index.js
<button class="btn btn-success">Install</button>
// Client Side Ajax Script
<script>
$('button').click(function () {
$.post('/page', {data: 'blah'}, function (data) {
console.log(data);
});
}, 'json');
</script>
app.js
app.post('/page', function (req, res) {
calling.aFunction();
res.send('A message!');
});
您应该看到一条消息!"在浏览器控制台中.
You should see "A message!" in the browser console.
这篇关于Ajax和Node.js的简单按钮单击示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!