2012-04-20 48 views
2

我无法将元素推送到作品数组中。控制台日志返回合适的对象,但他们不会被推到阵列...这里是我的代码:Javascript推送方法不起作用

var works = new Array(); 
    $(window).ready(function() 
    {  

     $.getJSON('AJAX/getWorks.php', function(data) { 
      $.each(data, function(key, val) { 
      console.log(val); 
      works.push(val); 
      }); 
     }); 
     console.log(works); 
    }); 

而且JSON对象:

Object 
date: "2012-04-08 17:53:58" 
description: "sadasd" 
id: "2" 
link: "sadasd" 
name: "dsad" 
objects: null 
position: "2" 
__proto__: Object 

任何人都看到我在做什么错误?在此先感谢您的答案...

+0

丢失的右括号是复制/粘贴错误吗? – 2012-04-20 16:29:23

+1

你怎么知道他们不在阵列中?你在哪里输出数组?你确定你没有在ajax请求完成之前记录数组吗? – 2012-04-20 16:30:09

+0

如果将调试语句更改为'console.log(val,works)',该怎么办? – apsillers 2012-04-20 16:30:30

回答

5

您在代码中提前记录数组。 console.log将在ajax请求完成之前运行,因为ajax是异步的。

$.getJSON('AJAX/getWorks.php', function(data) { 
       $.each(data, function(key, val) { 
       console.log(val); 
       works.push(val); 
       }); 
       console.log(works); // move this here so the array is logged after the ajax request finishes. 
      }); 

编辑

如果你想使用该变量Ajax请求后,你可以做以下

创建一个函数来容纳Ajax请求

function getWorks() 
{ 
    return $.getJSON('AJAX/getWorks.php', function(data) { 
       $.each(data, function(key, val) { 
       works.push(val); 
       }); 
} 

然后你就可以请执行以下操作以确保ajax请求已完成。

$.when(getWorks()).then(function(){ 
    // you can access the array in here because the ajax has finished executing 
}); 
+2

是的,在AJAX调用完成之前,OP中的日志代码正在运行。 – jmoerdyk 2012-04-20 16:40:40

+0

不,我不这么认为......我记录在document.ready中,在getJson函数后面,所以对象必须已经初始化... – hjuster 2012-04-20 16:41:09

+0

没有人看我的例子吗?你让人难以置信!正是这个例子减去JSON(它不能被正确测试)并且包括全局变量。啧。 – rlemon 2012-04-20 16:47:48