调用[重复]时,具有ajax事件的函数返回undefined

问题描述 投票:-3回答:1

这个问题在这里已有答案:

我有一个名为'getAuthor'的函数,里面有一个运行的ajax事件(参见下文)

function getAuthor(id){
    $.get('http://www.connectnigeria.com/articles/wp-json/wp/v2/users/74',function(e){
        var author = e.name;
        console.log(author);
        return author;
    });
}

尝试从控制台运行,你会看到它返回“undefined”,而console.log显示ajax调用的预期响应。

任何想法都有帮助吗?

javascript jquery ajax
1个回答
0
投票

除非函数有明确的返回,否则它将始终返回undefined

在控制台中它是未定义的,因为函数getAuthor没有返回任何东西。不要与$.get的回归相混淆。

console.log语句位于此异步函数中。要从函数getAuthor返回,请尝试此操作

function getAuthor(id){
    return $.get('http://www.connectnigeria.com/articles/wp-json/wp/v2/users/74',function(e){
        var author = e.name;
        console.log(author);
        return author;
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.