繁体   English   中英

为什么我的jQuery .ajax()路由的.done()方法未在NodeJS,Express和Mongoose项目中触发?

[英]Why is my jQuery .ajax() route's .done() method is not firing in my NodeJS, Express and Mongoose project?

试图理解为什么在下面调用销毁路径后,尽管在我的ajax调用中,但在客户端(jQuery)上我的.done()方法却无法运行?

我期望的行为 :我的/:id/destroy路由应该运行,通过id破坏引号,然后查询数据库中所有现有的引号。 这应该在jQuery .done()方法中交回,以附加到现有的HTML数据中(以显示新的引号,而不必重新加载页面)。

发生的事情是:当销毁路由运行时,返回json数据,但是.done()方法从不在jQuery ajax中运行-另外,表单提交(尽管我使用event.preventDefault(); -我有也尝试return false但表单仍发送)。 结果页面是带有所需引号的GET响应(因此查询本身正在运行),但是我不知道我是否格式化了JSON格式不正确或是否处理了来自jQuery ajax的回调请求。

有任何想法吗? (请注意,ejs,express,body-parser和猫鼬是该项目中的依赖项)

我有以下HTML和jQuery,可对/ destroy URL运行AJAX请求,如下所示:

我的路线

app.get('/:id/destroy', function(req, res){
    // removes quote by id:
    Quote.remove({_id: req.params.id}, function(err){
        if (err){
            console.log('Remove was unsuccessful...', err);
            res.json(err);
        };
        console.log('DELETED');
        // queries for allQuotes:
        Quote.find({}).sort({'vote':'desc'}).exec(function(err, allQuotes){ 
            if (err){
                console.log(err);
            } else {
                res.json(allQuotes[0]);
            }
        })
    });
});

我的jQuery

$('form.destroy').submit(function(event){
    event.preventDefault();
    $.ajax({
        url: '/'+$(this).attr('mongoID')+'/destroy',
        method: 'GET',
        data: $(this).attr('mongoID').serialize(),
    })
    .done(function(allQuotes){ // this never runs (Why?)
        console.log('Showing quotes now again after delete...');
        buildAllQuotes(allQuotes); // this never runs but appends response to html data
    })
    .fail(function(err){
        console.log('Error with deletion...', err);
    })
    .always(function(){
        console.log('Done');
    })
});

我的HTML

<form action="/'+allQuotes[x]._id+'/destroy" class="destroy" method="GET" mongoID="'+allQuotes[x]._id+'">
    <input type="submit" value="Delete">
</form>

form元素中删除action属性。 这将阻止提交表单。

的HTML

<form class="destroy" method="GET" mongoID="'+allQuotes[x]._id+'">
    <input type="submit" value="Delete">
</form>

由于form是在ajax调用之后提交的,因此您的done方法可能无法触发。

带有虚拟action属性的小提琴,

https://jsfiddle.net/balasuar/atg5m6ym/7631/

暂无
暂无

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

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