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

2024-03-16

我使用 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>

Ajax 内容也在 page.ejs 主体中

        $('#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);
                }                                           
            });
        });

The 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处的表数据而不重新加载页面?

Thanks!


您可以删除现有的 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>');
    }
})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Ajax、Json 和 Node.js 刷新表数据 的相关文章

随机推荐