javascript - 全局传递 xhr onload 函数的值

标签 javascript json node.js xmlhttprequest

在我正在创建的应用程序中,我有以下 XMLHttpRequest,我试图将 xhr.onload() 中的 data 结果传递到一个数组中这是在同一个父函数中创建的。

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

在此之下,我有一个数组的构建 block ,我正在尝试将数据结果传递到轨道字符串中。

var metadata = {
        id: val,
        title: title,
        url: posturl,
        track: data.permalink_url
      };

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

最佳答案

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;

关于javascript - 全局传递 xhr onload 函数的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20207405/

相关文章:

javascript - 当 Objective-C dom 更新准备好从 webview 启动时收到通知

javascript - Linkedin API 注册按钮 - 我是初学者

node.js - Sequelize 与 sql 存储过程。在我的情况下我应该使用什么?

javascript - 展平嵌套回调

c# - Rest Sharp 没有序列化日期

node.js - Node process.env.VARIABLE_NAME 返回未定义

JavaScript - 对象的函数引用其字段

javascript - 方法在 React.js 基于类的组件中无法按预期工作

json - 自定义 MarshalJSON() 永远不会在 Go 中被调用

php - 删除 while 循环中的最后一个逗号 - PHP