未定义使用 HTTP GET 请求返回对象

Returning object using HTTP GET request is undefined

本文关键字:请求 返回 对象 GET HTTP 未定义      更新时间:2023-09-26

我正在发出GET请求,以便通过链接获取YouTube的视频数据对象。我想我不明白这里是当我console.log返回的请求时,它被记录到浏览器控制台

function videoThumb(url){
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      var myArr = JSON.parse(xmlhttp.responseText);
      //printing to the console
      console.log(myArr);
      //object returned per call
      return myArr;
    }
  }
  xmlhttp.open("GET", url, true);
  xmlhttp.send();
}
  
var obj = videoThumb("https://www.googleapis.com/youtube/v3/videos?part=statistics&id=QIc00XImJmA&key=AIzaSyCC0R6ZmeHW0pXVQxE7RJPTt5_JvwTGwXA")
//obj should have returned value from `videoThumb` 

但是当我将返回的对象值存储在变量 obj 中时,再次调用 obj 返回undefined

定义一个超出xmlhttp范围的变量。

function videoThumb(url){
     var r = false,
         xmlhttp = new XMLHttpRequest();
     xmlhttp.onreadystatechange = function() {
         if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
             // update the variable response
             r = JSON.parse(xmlhttp.responseText);
         }
     }
     xmlhttp.open("GET", url, false); // change async to false to wait for response although this is bad!
     xmlhttp.send();
     return r;
}
var obj = videoThumb("https://www.googleapis.com/youtube/v3/videos?part=statistics&id=QIc00XImJmA&key=AIzaSyCC0R6ZmeHW0pXVQxE7RJPTt5_JvwTGwXA");
//obj should have returned value from `videoThumb` 
console.log(obj);

上述解决方案对时间和网页性能有点不利。我使用这个时遇到了以下错误,并认为这是因为我在页面加载时调用了该函数。

主线程上的同步 XMLHttpRequest 已被弃用,因为它会对最终用户的体验产生不利影响。如需更多帮助,请查看 https://xhr.spec.whatwg.org/。

我推荐的最佳方法是使用如下所示的回调函数。

    function videoThumb(url, callback){
         var xmlhttp = new XMLHttpRequest();
         xmlhttp.onreadystatechange = function() {
             if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                 // update the variable response
                 callback(JSON.parse(xmlhttp.responseText));
             }
         }
         xmlhttp.open("GET", url, true);
         xmlhttp.send();
    }
videoThumb("https://www.googleapis.com/youtube/v3/videos?part=statistics&id=QIc00XImJmA&key=AIzaSyCC0R6ZmeHW0pXVQxE7RJPTt5_JvwTGwXA", function(response){
    console.log(response);
});