简体   繁体   中英

Simple button click example with Ajax and Node.js?

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.

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.

This is all happening on /page

index.hjs file

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM