[英]Ajax update and remove table rows with node.js and mongoose
我正在用Node.js制作ajax表。 我可以更新行而不刷新整个页面,也可以删除任务。 由于以下原因,它并不完美,请查看图片。
当我更新某些行并单击“删除”按钮时,它不起作用。 但刷新整个页面后,它运行良好。 也许这是一个非常冗长的问题,如果您没有足够的时间-请参阅js文件,这里有问题的关键...好吧,那么代码是:
html :如果我加载页面,该页面将找到数据库并显示每个数据库。 我认为这没问题。
<table id="tb-docs">
<thead>
<tr>
<th width="50">Active</th>
<th width="300">Subject</th>
<th>Content</th>
<th width="110">Action</th>
</tr>
</thead>
<tbody>
<% posts.forEach( function ( post, index ){ %>
<tr>
<td><input type="checkbox"/></td>
<td><%= post.Subject %></td>
<td><%= post.Content %></td>
<td><button onclick="deleteRow(this,'<%= post._id %>')">Remove</button>
</td>
</tr>
<% }); %>
</tbody>
</table>
js :我强烈怀疑updateRow函数中的'append()'。 也许有什么问题,
function updateRow(subject, content){
$.ajax({
url: "/",
type: "POST",
data: { 'subject': subject, 'content': content },
success: function(data){
$('#tb-docs').append('<tr>' +
'<td><input type="checkbox" checked/></td>' +
'<td>'+subject+'</td>' +
'<td>'+content+'</td>' +
// *** Here Appended button is not worked !!!! ***
'<td><button onclick="deleteRow('+this+','+data+')">Remove</button></td>' +
'</tr>');
}
});
}
function deleteRow(obj, id) {
$.ajax({
url: "/dbs/destroy/"+id,
type: "POST",
data: { 'id': id },
success: function(data){
$(obj).closest('tr').fadeOut(300,function(){
$(obj).closest('tr').remove();
});
},
});
}
服务器(node.js)
// update row handler ===============
app.post('/', function (req, res){
new posts({
Subject: req.body.subject,
Content: req.body.content,
Active: true
}).save(function (err, post) {
if (err) return next(err);
res.send(post._id);
});
});
// delete row handler ===============
app.post('/dbs/destroy/:id',function (req, res){
posts.findById(req.params.id, function (err, post){
if (err) res.send(err) ;
post.remove(function(err, todo, next){
if(err) return next(err);
res.sendStatus(200);
});
});
});
我挣扎了两天。 表中的此追加行只是技巧,对吗? 因此,我认为附加的“按钮”无效,但重新加载的页面“按钮”有效。 然后,如何使用附加按钮执行操作?
我认为以另一种方式,将此表html文件和ajax调用分开。 但是我有很多桌子,所以这是非常艰苦的工作,而不是有效的方法。 你能告诉我什么是真正的问题吗? 不好意思,因为它与数据库有关。 无论如何,感谢您的阅读!
无需使用'+ this +',只需在deleteRow按钮的onclick函数中键入此内容即可。
function updateRow(subject, content){
$.ajax({
url: "/",
type: "POST",
data: { 'subject': subject, 'content': content },
success: function(data){
$('#tb-docs').append('<tr>' +
'<td><input type="checkbox" checked/></td>' +
'<td>'+subject+'</td>' +
'<td>'+content+'</td>' +
// *** Here Appended button is not worked !!!! ***
'<td><button onclick="deleteRow(this,'+data+')">Remove</button></td>' +
'</tr>');
}
});
}
function deleteRow(obj, id) {
$.ajax({
url: "/dbs/destroy/"+id,
type: "POST",
data: { 'id': id },
success: function(data){
$(obj).closest('tr').fadeOut(300,function(){
$(obj).closest('tr').remove();
});
},
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.