在其回调方法之外访问JSON对象 [英] Accessing a JSON object outside its callback method

查看:208
本文介绍了在其回调方法之外访问JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个函数,该函数将连接到服务器并检索JSON对象.它将处理它并返回一个普通数组,该数组具有要在某些HTML标记中加载的值.我知道可以使用其他方法来完成此操作,但是我正在使用以下代码.

I am writing a function, which will connect to a server and retrieve a JSON object. It will process it and return a normal array with values to be loaded in some HTML tag. I know it can be done using other ways, but I am using the following code.

var names = new Array();
function fetch (key) {
  var url = 'server/server.php?key=' + key
  $.getJSON(url , sett = function(data) {
    $.each(data, function(key, value){
      names[key] = value['name'];
    });
    console.log(names);//works and print the values
  });
  console.log(names);//doesn't work, shows and empty array
}

我想返回一个数组,该数组将保存每个jQuery过滤的值,因此该函数可以用作任何大型应用程序的标准函数.怎么做?

I want to return an array which will hold the values filtered by jQuery each, so this function can work as a standard function for any big application. How it can be done?

推荐答案

就像注释中提到的那样,您的ajax请求将花费一些时间(时间短,但仍然很长),因此您的console.log位于ajax之外调用将在ajax调用完成之前执行,显示原始的空数组.

Like mentioned in comments, your ajax request will take some time (short amount of time, but still time), so your console.log located outside of the ajax call will execute before the ajax call is complete, showing the original, empty array.

您可以在fetch函数中添加回调参数...

You could add a callback parameter to your fetch function...

所以...

function fetch (key, callback) {
  var url = 'server/server.php?key=' + key
  $.getJSON(url , sett = function(data) {
    $.each(data, function(key, value){
      names[key] = value['name'];
    });
    // call callback inside the getJSON callback    
    callback && callback.call(this, names);
  });
}

现在,您的回调函数会将您的names数组作为参数1.

Now, your callback function will have your names array as argument one.

fetch(some_key, function(names){
  console.log(names); //should work!
});

这篇关于在其回调方法之外访问JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆