jquery无法读取未定义的属性'done' - 避免这种情况 [英] jquery Cannot read property 'done' of undefined - avoid this

查看:196
本文介绍了jquery无法读取未定义的属性'done' - 避免这种情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回结果的函数(或不返回)。问题是当它没有返回我在控制台中得到的任何值时消息

I have a function which returns results (or not). The problem is when it does not return any value I get in the console the message


无法读取未完成的属性'done'

cannot read property 'done' of undefined

这是真的,我确实理解这个问题。此外,此错误不会使我的代码停止工作,但我想知道是否有机会避免这种情况?

Which is true and I do understand the problem. Also, this error doesn't make my code stop working, but I would like to know if there's any chance of avoiding this?

ajax中的函数是:

The function in ajax is:

function getDelivery(){
    var items = new Array();

    $("#tab-delivery tr").each(function(){
        items.push({"id" : $(this).find('.form-control').attr('id'), "id_option" : $(this).find('.form-control').val()});
    });

    if(items.length > 0){
        return $.ajax({
            url: 'response.php?type=getDelivery',
            type: 'POST',
            data: {content: items}
        });
    }
}

为了调用它,我使用:

getDelivery().done(function(data){ // the problem is here
    if(data == false){
        return;
    }
});

那么,有什么方法可以避免错误吗?我试过以下没有成功:

So, is there any way of avoid the error? I have tried without success the following:

if(items.length > 0){
    return $.ajax({
        url: 'response.php?type=getDelivery',
        type: 'POST',
        data: {content: items}
    });
}else{
    return false;
}

我收到错误:


Uncaught TypeError:undefined不是函数

Uncaught TypeError: undefined is not a function


推荐答案

你可以只返回一个延迟,这样 done()回调不会产生错误,你可以选择解决它

You could just return a deferred, that way the done() callback won't generate errors, and you can choose to resolve it or not

if(items.length > 0){
    return $.ajax({
        url: 'response.php?type=getDelivery',
        type: 'POST',
        data: {content: items}
    });
}else{
    var def = new $.Deferred();
    def.resolve(false);
    return def;
}

FIDDLE

这篇关于jquery无法读取未定义的属性'done' - 避免这种情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆