简体   繁体   English

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

[英]How use the success call back in a delete ajax [NODE.JS]

I'm using the following code to delete a collection in my db: 我正在使用以下代码删除数据库中的集合:

Client: 客户:

$('.destroy').click(function() {

    if(confirm("Are u sure?")) {
        $.ajax({
            type: 'DELETE',
            url: '/destroy/' + dataId,
            success: function(response) {
                console.log('Success');
            }
        });
    } else {
        alert('Cancelled');
    }
});

Server: 服务器:

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!');
        }
    });
});

Is working, if i click in the destroy button and reload the page, the collection will not be there, but the success callback function with the: [console.log('Success');] is not running.. 正在运行,如果我单击销毁按钮并重新加载页面,则该集合将不存在,但是带有[console.log('Success');]的成功回调函数未运行。

I need send a callback from the server to the client ir order to make the success function run??? 我需要从服务器向客户端ir发送回调,以使成功功能运行???

How make the console.log('Success'); 如何使console.log('Success'); run?? 跑??

Thanks. 谢谢。

The ajax call probably just times out, as it's never getting a response back from the server. Ajax调用可能只是超时,因为它永远不会从服务器返回响应。

Send a response from the server 从服务器发送响应

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');
        }
    });
});

Then catch it 然后抓住它

$.ajax({
    type    : 'DELETE',
    url     : '/destroy/' + dataId,
    success : function(response) {

       if ( response === 'error' ) {

           alert('crap!');

       } else if (response === 'success' ) {

           alert('worked fine!');

       }

    }
});

This is a simplified example, you can return whatever you like, send statusCodes or whatever. 这是一个简化的示例,您可以返回所需的任何内容,发送statusCodes或任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM