Javascript数组未定义

时间:2014-04-19 16:20:51

标签: javascript jquery arrays json

目前我正在将JSON对象返回给javascript数组。该数组包含所有正确的数据(我使用Firebugs console.debug()功能来检查),但是当我尝试使用数组中的数据时,它表示它未定义。

这是返回JSON对象的函数:

function populateVals(sess, stepSize) {
    var items = new Array();
    var run;

    // Check if one or multiple files need to be processed
    if(sess.indexOf("|") >= 0) {
        alert("Multiple files");
    } else {    
        $.ajax({
            url:"json/getVals.php",
            data: {email: GLOBAL.email, actDate: sess, stepSize: stepSize},
            type: "POST",
            dataType: "json",

            success: function(json) {
                items.push(json);
            },
            error: function (xhr, status, errorThrown) {
                alert( "Sorry, there was a problem!" );
            }
        });
    }
    return items;
}

以下是尝试使用该数组的代码段代码:

var results = new Array();
    results = populateVals(sess, stepSize);
    console.debug(results);

    GLOBAL.results = results.distances; //used by toExcel

    var data = [];
    var data2 = [[0,0],[16.15,0]]; //try to draw alternate x axis showing minute-miles
    var x = 0.0;
    var y;

    for(var i = 0;i < results.distances.length; i++){
        y = results.distances[i];
        data.push([x,y]); //change a plot point y to [x,y]
        //x += 1/10;
        x += stepSize;
    }

未定义的错误发生在上述段的以下行中,其中results.distance未定义:

for(var i = 0;i < results.distances.length; i++){

此外,这是从firebug转储数组,它有助于显示我实际参考的距离(距离本身就是一个数组):

Object { distances=[26], stepSize=1, TotalTimeSeconds=1396951626, more...}

TotalDistanceMeters
    2462.86

TotalTimeSeconds
    1396951626

distances
    [0, 0.40603201156379, 0.81206402312758, 23 more...]

0
    0

1
    0.40603201156379

2
    0.81206402312758

3
    0

4
    0

5
    0

6
    0

7
    0

8
    0

9
    0

10
    0

11
    0

12
    0

13
    0

14
    0

15
    0

16
    0

17
    0

18
    0

19
    0

20
    0

21
    0

22
    0

23
    0

24
    0

25
    0

非常感谢您提供的任何帮助

4 个答案:

答案 0 :(得分:2)

jQuery AJAX默认为Async。因此,当您调用函数results = populateVals(sess, stepSize);时,它会向服务器发出请求并继续执行下一个代码。因此,当您说results.distances时,服务器可能未返回结果,从而导致出现未定义的错误。

此外,您使用响应中的对象覆盖结果数组。检查一下。

答案 1 :(得分:0)

与其他海报建议的一样,你应该使用一个回调函数,因为populateVals每次都会返回一个空数组,因为AJAX调用没有完成。

假设数据已从服务器正确返回(使用回调),则结果是一个数组,这意味着您需要遍历所有&#34;项目&#34;在该数组中,然后查看每个项目中的距离数组。

引用第一个项目的距离数组:

results[0].distances

这是使用回调函数的可能替代方案。它看起来你不需要返回一个数组,因为每次数组只有1项:

function processData(json){
    var results = json;
    console.debug(results);

    GLOBAL.results = results.distances; //used by toExcel

    var data = [];
    var data2 = [[0,0],[16.15,0]]; //try to draw alternate x axis showing minute-miles
    var x = 0.0;
    var y;

    // for each distances value in the result
    for(var i = 0;i < results.distances.length; i++){
        y = results.distances[i];
        data.push([x,y]); //change a plot point y to [x,y]
        //x += 1/10;
        x += stepSize;
    }
}

function populateVals(sess, stepSize) {
    // Check if one or multiple files need to be processed
    if(sess.indexOf("|") >= 0) {
        alert("Multiple files");
    } else {    
        $.ajax({
          url:"json/getVals.php",
          data: {email: GLOBAL.email, actDate: sess, stepSize: stepSize},
          type: "POST",
          dataType: "json",
          success: function(data) {
            processData(data);
          },
          error: function (xhr, status, errorThrown) {
            alert( "Sorry, there was a problem!" );
          }
        });
    }
}

答案 2 :(得分:0)

问题是$ .ajax()方法是异步的。换句话说,您的代码将在服务器尚未响应时继续执行。因此,您的populateVals()方法将返回一个空数组。

解决此问题的唯一方法是向函数添加某种回调参数,然后获取传递的值并进行任何进一步处理。

答案 3 :(得分:0)

populateVals(sess, stepSize)中的ajax调用是异步的,这意味着函数将在ajax完成之前返回。添加async:false以强制同步行为:

    $.ajax({
        url:"json/getVals.php",
        data: {email: GLOBAL.email, actDate: sess, stepSize: stepSize},
        type: "POST",
        dataType: "json",
        async: false, //async

        success: function(json) {
            items.push(json);
        },
        error: function (xhr, status, errorThrown) {
            alert( "Sorry, there was a problem!" );
        }
    });