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

时间:2022-02-23 16:49:21

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:

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

page.ejs

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 content that also is in page.ejs body

页面中的Ajax内容。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 call this function:

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

Function called in node.js server:

函数称为节点。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
        });
    });

My question is: how to refresh table data at page.ejs in success ajax callback without reload the page?

我的问题是:如何在页面中刷新表数据。成功的ejb ajax回调不重载页面?

Thanks!

谢谢!

1 个解决方案

#1


3  

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

您可以删除现有的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>');
    }
})

#1


3  

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

您可以删除现有的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>');
    }
})