如何使用Ajax、Json和Node.js刷新表数据

How to refresh table data using Ajax, Json and Node.js

本文关键字:js 刷新 数据 Node 何使用 Ajax Json      更新时间:2023-09-26

我使用Node.js作为服务器端,使用express和Twitter Bootstrap作为前端。该页面有一个带有表单和提交按钮的对话框;表单是通过Jquery Ajax调用提交的,以便在node.js服务器响应后不要重新加载页面。以下是我想做的三个步骤:

page.ejs

<table id="tblProgs" class="table table-bordered table-hover table-striped dataTable">
<thead>
    <tr>
        <th>
            Column
        </th>
   </tr>
</thead>
<tbody>
     <% datas.forEach(function(data) { %>
          <tr>
              <th width="15%">
                  <%- data._column %>
              </th>
          </tr>
     <% }) %>
</tbody>
</table>

page.ejs正文中的Ajax内容

        $('#formId').submit(function (e){
            e.preventDefault();
            $.ajax({
                type: 'POST',
                data: JSON.stringify(data),
                cache: false,
                contentType: 'application/json',
                datatype: "json",
                url: '/route/to/nodejs',
                success: function (result) {                            
                    console.log("Here are the response in json format: " + result);
                }                                           
            });
        });

url /route/to/nodejs调用此函数:

node.js服务器中调用的函数:

    query = "SELECT * FROM table_name";
    sequelize.query(query, {
        type: sequelize.QueryTypes.SELECT
    }).success(function (result) {
            var response = {
                data : result,                      
            }
            res.send(response); 
    }).catch(function (error) {
        res.render('server-error', {
            user: user,
            session: req.session,
            error: error
        });
    });

我的问题是:如何在成功ajax回调中刷新page.ejs上的表数据而不重新加载页面

谢谢!

您可以删除现有的tbody内容,然后在jQuery AJAX回调中使用jQuery重新渲染。类似。。

success: function (result) {     
    $('tbody').empty();
    for (var data in result) {
       $('tbody').append('<tr><th width="15%">'+result[data]._column+'</th></tr>');
    }
})