javascript 使用 Ajax 和 Node.js 的简单按钮单击示例?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27158186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 07:02:39  来源:igfitidea点击:

Simple button click example with Ajax and Node.js?

javascriptajaxnode.jsexpress

提问by Web Hopeful

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.

我是 Ajax 和 Node.js + Express 的新手。在这一点上,我试图弄清楚如何通过按钮与前端和后端进行通信。

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.

我在 HTML 页面上有一个按钮,我想用它从后端调用函数并将文本输出到客户端。

Here is what I've pieced together for what I need but I am looking for an example on how this could be done.

这是我为我需要的东西拼凑起来的东西,但我正在寻找一个关于如何做到这一点的例子。

This is all happening on /page

这一切都发生在 /page

index.hjs file

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 file

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?

这些是我需要的所有部分以及需要编辑哪些部分才能使此功能正常工作吗?

回答by takinola

index.js

索引.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

应用程序.js

app.post('/page', function (req, res) {
    calling.aFunction();
    res.send('A message!');
});

You should see "A message!" in the browser console.

您应该会看到“一条消息!” 在浏览器控制台中。