XMLHttpRequest返回未定义

KH

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

这是一个非常基本的要求,我不明白为什么会这样

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

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

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语句,并且它不会从main函数中返回。

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章