全局传递xhr onload函数的值

lea*_*rrr 7 javascript json xmlhttprequest node.js

在我正在创建的应用程序中,我有以下XMLHttpRequest,并且我正在尝试将data内部结果传递xhr.onload()到在同一父函数中创建的数组中.

var url = 'http://api.soundcloud.com/resolve.json?'+resource+'&'+CLIENT_ID;
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onload = function(){
    var data = JSON.parse(xhr.responseText);
    console.log(data.permalink_url);
};
xhr.send();
Run Code Online (Sandbox Code Playgroud)

在这下面我有一个数组的构建块,我试图将数据的结果传递给轨道字符串.

var metadata = {
        id: val,
        title: title,
        url: posturl,
        track: data.permalink_url
      };
Run Code Online (Sandbox Code Playgroud)

到目前为止我尝试的所有东西要么返回,undefined要么function现在我完全没有想法......

Exp*_*lls 5

Ajax异步执行(通常).这对于Ajax的工作方式至关重要.这意味着,你不能在计算onload连法必火,或者如果它会火.这意味着所有依赖于xhr.responseText(HTTP请求的结果)的代码都必须在回调本身内完成.例如:

xhr.onload = function () {
    // This will execute second
    doStuffWithData(JSON.parse(xhr.responseText));
}
// This will execute first
xhr.send();
var anything = anythingElse;
Run Code Online (Sandbox Code Playgroud)