XMLHttpRequest returning undefined



我正在尝试通过我的函数发送此HTTP请求,但无论如何它都返回未定义

这是一个非常基本的请求,我不明白为什么会发生这种情况

如果我将 URL 复制并粘贴到我的浏览器中,它可以工作并显示所需的 JSON

我在浏览器的控制台上使用随机 ID 和我的 API 密钥尝试了此功能,但仍然返回未定义

function getSummary(id){
let url2=`https://api.spoonacular.com/recipes/${id}/summary?apiKey=${key}`;
let xhr2=new XMLHttpRequest();
xhr2.responseType='json';
xhr2.onreadystatechange=()=>{
if(xhr2.readyState==XMLHttpRequest.DONE){
return xhr2.response;
}
}

xhr2.open('GET',url2);
xhr2.send();
}

指向 API 文档的链接

您在箭头函数中使用 return 语句,它不会从主函数返回。

xhr2.onreadystatechange=()=>{
//returns out of this function ^
if(xhr2.readyState==XMLHttpRequest.DONE){
return xhr2.response;
}
}

与其创建一个函数来返回响应文本,不如运行一个函数,将响应文本作为参数:

let url2=`https://api.spoonacular.com/recipes/${id}/summary?apiKey=${key}`;
let xhr2=new XMLHttpRequest();
xhr2.responseType='json';
xhr2.onreadystatechange=()=>{
if(xhr2.readyState==XMLHttpRequest.DONE){
//seperate function
run(xhr2.response);
}
}    
xhr2.open('GET',url2);
xhr2.send();
function run(text){
console.log(text);
};

最新更新