2012-04-19 71 views
1

使用json返回的数据填充现有数组时,我没有什么麻烦。 这里是我有使用json数据填充现有数组

myarr=[]; 
function fillarr() 
    { 
    $.getJSON("test.php?c=10",function(data) 
      { 
      $.each(data, function(key, val) 
        { 
        myarr.push(data[val]); 
        } 
        }); 
      }); 
    } 

我的问题是,该阵列是emty的功能外。 请帮忙。

+0

什么返回的数据看起来会更快?它是一个对象字面量还是数组? “myarr”的范围是什么? – Joseph 2012-04-19 08:41:31

回答

1
myarr=[]; 
function fillarr() 
    { 
    $.getJSON("test.php?c=10",function(data) 
      { 
      $.each(data, function(key, val) 
        { 
         myarr.push(val); 
         console.log(myarr); // you will myarr here, not out side 
        } 
        }); 
      }); 
     console.log(myarr); // wont get 
    } 

myarr在ajax请求完成后及时获取其内容。因此console之外的$ .getJSON在请求完成之前执行。

+0

感谢您的回复,但没有任何区别。 这些值仅在函数中可用,不在函数外部。 – BSDGuy 2012-04-19 08:43:41

1
myarr=[]; 
function fillarr() 
{ 
    $.getJSON("test.php?c=10", function(data) { 
     $.each(data, function(key, val) { 
      myarr.push(val); 
     }); 
     doSomethingNowThatTheArrayIsActuallyPopulated(); 
    }); 
} 

fillarr(); 

console.log(myarr); // This will print an empty array, it hasn't been populated yet. 

function doSomethingNowThatTheArrayIsActuallyPopulated() { 
    console.log(myarr); // This will print the array which now contains the json values 
} 
+0

返回的数据是一个数组。 – BSDGuy 2012-04-19 08:54:06

+0

谢谢。那是ist。非常感谢你。 – BSDGuy 2012-04-19 09:27:26

0

如果返回数据是一个对象,则更容易将jQuery.each推送到数组中。

function fillarr(){ 
    $.getJSON("test.php?c=10",function(data){ 
     $.each(data, function(key, val){ 
      myarr.push(val); 
     }); 
    }); 
} 

如果返回的数据是一个数组,Array concat

function fillarr(){ 
    $.getJSON("test.php?c=10",function(data){ 
     myarr = myarr.concat(data); 
    }); 
} 
+0

返回的数据是一个数组。 – BSDGuy 2012-04-19 08:55:05

+0

然后concat会更好的工作 – Joseph 2012-04-19 08:55:53

+0

我试过所有的建议,谢谢。正在工作,但只在功能内。在功能外,阵列仍然是空的。 – BSDGuy 2012-04-19 08:55:56