私信  •  关注

Banana Cake

Banana Cake 最近回复了
5 年前
回复了 Banana Cake 创建的主题 » 如何从EJS、Javascript写入MongoDB数据库?

谢谢大家的帮助。我没有意识到我可以使用POST方法而不需要呈现或重定向到某个页面。我还发现AJAX可以很容易地发送POST请求。

后端:

const express = require('express');
const router = express.Router();

router.post('/remove-device', (req, res) => {
    //some code for deleting from mongo DB
    console.log('Success');
    res.send('ok');
});

module.exports = router;

前端:

<table id="table">
        <thead>
          <tr>
            <th data-field="name">Device name</th>
            <th data-field="receivingKey">Receiving key</th>
            <th data-field="operate" data-formatter="operateFormatter" data-events="operateEvents"></th>
          </tr>
        </thead>
      </table>

      <script>
        var $table = $('#table');
        var data = <%- JSON.stringify(devices) %>;

        function operateFormatter(value, row, index) {
          return [
            '<a class="like" href="javascript:void(0)" title="Like">',
            '<i class="fa fa-heart"></i>',
            '</a>  ',
            '<a class="remove" href="javascript:void(0)" title="Remove">',
            '<i class="fa fa-trash"></i>',
            '</a>'
          ].join('')
        }

        window.operateEvents = {
          'click .like': function (e, value, row, index) {
            alert('You click like action, row: ' + JSON.stringify(row))
          },
          'click .remove': function (e, value, row, index) {
            $.ajax({
              method: "POST",
              url: "/intr/remove-device",
              data: { deviceName: row.name },
            }).done(function (data) {});
          }
        }

        $(function () {
          $('#table').bootstrapTable({ data: data });
        });