我使用以下代码删除数据库中的集合:
客户:
$('.destroy').click(function() {
if(confirm("Are u sure?")) {
$.ajax({
type: 'DELETE',
url: '/destroy/' + dataId,
success: function(response) {
console.log('Success');
}
});
} else {
alert('Cancelled');
}
});
服务器:
app.get('/destroy/:id', function(req, res) {
var id = req.param("id");
MyModel.remove({
_id: id
}, function(err){
if (err) {
console.log(err)
}
else {
console.log('Collection removed!');
}
});
});
正在工作,如果我单击销毁按钮并重新加载页面,集合将不存在,但成功回调函数如下:[console.log('Success');]
未运行..
我需要从服务器向客户端发送回调以使成功函数运行???
如何制作console.log('成功');运行??
谢谢。
最佳答案
ajax 调用可能只是超时,因为它永远不会从服务器返回响应。
从服务器发送响应
app.get('/destroy/:id', function(req, res) {
var id = req.param("id");
MyModel.remove({
_id: id
}, function(err){
if (err) {
res.end('error');
}
else {
res.end('success');
}
});
});
然后捕获它
$.ajax({
type : 'DELETE',
url : '/destroy/' + dataId,
success : function(response) {
if ( response === 'error' ) {
alert('crap!');
} else if (response === 'success' ) {
alert('worked fine!');
}
}
});
这是一个简化的示例,您可以返回任何您喜欢的内容,发送 statusCodes 或其他任何内容。
关于javascript - 如何在删除ajax中使用成功回调[NODE.JS],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27846278/