簡體   English   中英

如何使用Ajax,Json和Node.js刷新表數據

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM