这个问题在这里已有答案:
我有一个名为'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调用的预期响应。
任何想法都有帮助吗?
除非函数有明确的返回,否则它将始终返回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;
});
}