如何在不刷新html页面的情况下在表格上显示数据(使用nodejs&mysql ajax)

我正在尝试使用nodejs&express从mysql表中列出数据到我的html页面。

我正在使用nodejs&express,并希望使用ajax调用将mysql表中的数据列表到html页表中,以便在添加新项目时不会刷新页面。 目前,我直接显示使用快速语法的结果,并与数据表完美地工作。

我的表tablename-metrics_list数据在mysql中就像 –

id | 指标| custom_metrics

1 | abcd | abcd 2 | abcd | abcd 3 | abcd | abcd 

我的服务器端js代码如下 –

 router.get('/', function(req, res) { try { sess = req.session; if (sess.user != req.session.id) { console.log('SESSION EXPRED'); res.redirect('/'); } else { console.log('******LISTING FOR PORTAL'); connection.query('SELECT * FROM metrics', function(err, data) { if (err) { console.log("## Error in Portal ##"); } else { console.log("DATA " + JSON.stringify(data)); res.render('metrics-list', { metricsList: data }); } }); } } catch (ex) { console.log("Exception : " + ex); } }); 

我的HTML表格代码是:

  <table cellpadding="0" cellspacing="0" border="0" width="100%" class="table table-striped table-bordered dataTable no-footer" id="basic-datatable" role="grid" aria-describedby="basic-datatable_info"> <thead> <tr role="row"> <th class="sorting_asc" tabindex="0" aria-controls="basic-datatable" rowspan="1" colspan="1" aria-sort="ascending" aria-label="Rendering engine: activate to sort column descending" style="width: 40px;">Sr No</th> <th class="sorting" tabindex="0" aria-controls="basic-datatable" rowspan="1" colspan="1" aria-label="Browser: activate to sort column ascending" style="width: 80px;">Group</th> <th class="sorting" tabindex="0" aria-controls="basic-datatable" rowspan="1" colspan="1" aria-label="Browser: activate to sort column ascending" style="width: 80px;">Actions</th> </tr> </thead> <tbody> <%for(var j=0;j<metricsList.length;j++){%> <% if(metricsList[j].custom_metrics == '' || metricsList[j].custom_metrics == null) { %> <% } else { %> <tr class="gradeA odd" role="row"> <td class="sorting_1"><%=j+1%></td> <td ><%=metricsList[j].custom_metrics %></td> <td style="text-align: center;"> <a href="/metrics/delete?id=<%=metricsList[j].id%>" onclick="return confirm('Are you sure you want to delete this item?');"> <i class="glyphicon glyphicon-trash" ></i></a> </td> </tr> <% } %> <%}%> </tbody> </table> <!-- TABLE END --> 

我想弄清楚如何使用ajax列出表格,以便在mysql中添加数据时,它会立即显示在列表中,而不会刷新整个html页面。

您可以删除现有的tbody内容,然后在jQuery AJAXcallback中使用jQuery重新渲染。 就像是..

 success: function (result) { $('tbody').empty(); for (var data in result) { $('tbody').append('<tr class="gradeA odd" role="row"><td style="word-break: break-all;">data.custom_metrics</td></tr>'); } })