当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Returning object using HTTP GET request is undefined

问题描述:

I'm making a GET request in order to get video data object of YouTube through link. I think I don't understand here is when I console.log the returned request it is getting logged to the browser console

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`

网友答案:

Define a variable out of xmlhttp scope.

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);
分享给朋友:
您可能感兴趣的文章:
随机阅读: