如何使用 Ajax、Json 和 Node.js 刷新 table 数据
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>
Ajax也在page.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);
}
});
});
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
});
});
我的问题是:如何在 page.ejs 成功回调 ajax 刷新 table 数据而不重新加载页面?
谢谢!
您可以删除现有的 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>');
}
})
我使用 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>
Ajax也在page.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);
}
});
});
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
});
});
我的问题是:如何在 page.ejs 成功回调 ajax 刷新 table 数据而不重新加载页面?
谢谢!
您可以删除现有的 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>');
}
})