2014-01-17 169 views
0

我想返回一个json数组到一个函数并输出结果。以下是我想要实现的一个示例,但是'thisArray'会以'未定义'的形式出现。我究竟做错了什么?感谢反馈...JavaScript返回数组对象

<html> 
<head> 
<title>Test Array</title> 

function recipesTestObject(recId, recipe) 
{ 
this.recId = recId; 
this.recipe = recipe; 

} 

function initialise() { 


    $.getJSON ("/mealplanners2/apprequests/mealplanner.php?action=getRecipesByCat", { recCategory: 2 }, function(json) { 
     var recipeTest = new Array(); 
     $.each (json.recipes, function(){ 

     recipeTest[recipeTest.length] = new recipesTestObject(this['id'], this['recName']); 


     }); 

    return recipeTest; 

    }); 


    } 

    function display(thisArray) { 

for (var i=0; i < thisArray.length; i++) { 
    document.write("Name: "+thisArray[i].recipe+"<br>"); 

} 

    } 
    </script> 
    </head> 
<body> 
<script language="javascript"> 

var x; 

x = initialise(); 

display(x); 
</script> 
</body> 
</html> 
+0

除了重复之外,一旦你解决了异步问题,你会发现你不应该使用'document.write()',因为它会在页面加载后被调用。 –

回答

0

你返回它的成功回调函数内部,而不是从INITIALISE功能。

周围有这么多的方式,一种是利用回调:

function initialise(callback) { 

    $.getJSON ("/mealplanners2/apprequests/mealplanner.php?action=getRecipesByCat", 
    { recCategory: 2 }, function(json) { 
     var recipeTest = []; 
     $.each (json.recipes, function(){ 
      recipeTest.push(new recipesTestObject(this['id'], this['recName'])); 
     }); 
    callback(recipeTest); 
    }); 
} 

然后调用它像这样:

initialise(display); 
0

thisArrayundefined因为initialise没有返回值。

您可以通过使用一个回调函数解决这个问题:

function initialise(callback) { 
    $.getJSON("/mealplanners2/apprequests/mealplanner.php?action=getRecipesByCat", { 
     recCategory: 2 
    }, function (json) { 
     var recipeTest = []; 
     $.each(json.recipes, function() { 
      recipeTest.push(new recipesTestObject(this.id, this.recName)); 
     }); 
     callback(recipeTest); 
    }); 
} 

然后代替

var x; 
x = initialise(); 
display(x); 

,你可以这样做:

initialize(display); 

请注意,我使用[]而不是new Array()。这是初始化数组的首选方法。

我也使用recipeTest.push(...)而不是recipeTest[recipeTest.length] = ...,因为push是向数组添加项目的首选方法。您也可以使用this.id而不是this['id']