[英]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.