我正在尝试使用nodejs和express将mysql表中的数据列出到我的html页面。
我正在使用nodejs&express并且想要使用ajax调用将数据从mysql表列出到html页表,以便添加新项目时页面不会刷新。目前,我使用表达语法直接显示结果,并且与数据表完美配合。
我的表tablename-metrics_list在mysql中的数据就像-
id |指标 |自定义指标
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 AJAX 回调中使用 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>');
}
})
关于javascript - 如何在不刷新html页面的情况下在表上显示数据(使用nodejs和mysql ajax),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39811509/