javascript jquery无法读取未定义的属性“完成” - 避免这种情况

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23115928/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 00:21:51  来源:igfitidea点击:

jquery Cannot read property 'done' of undefined - avoid this

javascriptjqueryundefined

提问by Linesofcode

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

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

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?

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

The function in ajax is:

ajax中的函数是:

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

And to call it I use:

并称之为我使用:

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

And I get the error:

我得到错误:

Uncaught TypeError: undefined is not a function

未捕获的类型错误:未定义不是函数

回答by adeneo

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

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

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

小提琴