javascript - 如何在删除ajax中使用成功回调[NODE.JS]

标签 javascript jquery ajax node.js

我使用以下代码删除数据库中的集合:

客户:

$('.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/

相关文章:

javascript - Chrome 中快速挂 AJAX 删除后

javascript - Symfony2 将ajax请求数据传递给表单渲染 Controller

javascript - jQuery 数据表导出到 excelHtml5 HYPERLINK 问题

javascript - 在带有扩展的 map 中使用 Promise

javascript - 导航下拉菜单不适用于超时

jquery - 如何从responseText中获取具有完整Html页面的特定div内容

jquery - .each() 集合中的最后一个元素

javascript - Internet Explorer 不保存打开文件对话框中的路径

jquery - 如何在服务器端修改 CORS 请求(来自 IE8 或 IE9) - 以启用 Spring 绑定(bind)

php - AJAX 第二次请求和 IE6