简体   繁体   中英

How to refresh table data using Ajax, Json and 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>

Ajax content that also is in page.ejs body

        $('#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:

Function called in node.js server:

    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?

Thanks!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM