如何使用Ajax,JSON和Node.js的刷新表数据如何使用、数据、Ajax、JSON

2023-09-11 22:35:01 作者:仅有德幸福

我用Node.js的服务器端与前preSS和Twitter引导为前端。该页面有一个表单和一个提交按钮对话框;形式是通过jQuery的Ajax调用提交从node.js的服务器的响应后,没有重新加载页面。这里有三个步骤,希望我做的事:

I'm using Node.js as server-side with express and Twitter Bootstrap as front-end. The page has a dialog with a form and a submit button; the form is submitted through Jquery Ajax call for don't reload the page after the response from node.js server. Here are three steps would like I to do:

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体内

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

网址 /路由/到/ 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
        });
    });

我的问题是:如何到page.ejs在成功的Ajax回调不会重新加载页面刷新表数据

谢谢!

推荐答案

您可以删除现有的TBODY的内容,然后在jQuery的AJAX回调使用jQuery重新呈现。喜欢的东西..

You could remove the existing tbody content, and then re-render using jQuery in the jQuery AJAX callback. Something like..

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