返回AJAX阵列不能被复制到阵列 [英] Returned AJAX array not being copied to array

查看:93
本文介绍了返回AJAX阵列不能被复制到阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有简单的AJAX功能使用jQuery的从数据库返回的300个测试对象的数组。我可以看到数据返回,我可以使用萤火逐句通过第一循环,步入构造。

I have simple AJAX function that uses jQuery to return an array of 300 test objects from a database. I can see the data is returned, and I can use FireBug to step through the first loop and step into the constructor.

此数据被复制到一个JS数组。在code片段如下:

This data is copied to an JS array. The code fragment looks like:

    //retrieve star locations to display on page
    $.getJSON("stars.php?jsoncallback=?", function(data) {
    	for (var x=0, xx=data.length; x<xx; x++) {
//  		planetArray[x] = new Planet(data[x].xpos, data[x].ypos); // also doesn't work.
    		planetArray.push(new Planet(data[x].xpos, data[x].ypos));
    	}
    });

    for (var i=0, ii=planetArray.length; i<ii; i++) {
    	// display the data.
    }

萤火说 planetArray.length 为零。该行星的构造是这样的:

FireBug says planetArray.length is zero. The Planet constructor looks like:

function Planet(x, y) {
    this.x = x;
    this.y = y;
}

我觉得这是一个范围的问题,但我似乎无法弄清楚。在其它语言创建一个新对象意味着它存在于堆和生存的范围,但在这里它似乎消失在醚

I think it is a scoping issue but I can't seem to figure it out. In other languages creating a new object means it exists on the heap and survives the scope, but here it seems to disappear into the ether.

我如何返回数组及更高版本(甚至是在其他功能),将其推入我自己的数组使用?

How can I return an array and push it into my own array for use later (or even in another function)?

推荐答案

AJAX请求异步发生 - 你不等待它完成,然后再尝试和显示数据。

The AJAX request happens asynchronously - you're not waiting for it to complete before you try and display the data.

将显示code进入回调和它应该工作。

Move the display code into the callback and it should work.

这篇关于返回AJAX阵列不能被复制到阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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