2017-05-25 77 views
0

我有一个AJAX正从分贝值,并且将结果推入的数组:提取阵列 - 未定义

function pushPONFail(dt, ct) { 
    if (ct < 12) { 
     var tMon = parseInt(dt.getMonth())+1; 
     var tYear = dt.getFullYear(); 

     ct++; 
    } else { 
     return; 
    } 
    data = {"qType": 101, 
      "tbl": 'qualitypqa.dbo.centerthickness', 
      "month": tMon, 
      "year": tYear, 
      "type": 'Lotrafilcon B'}; 
    $.ajax({ 
     cache : false, 
     url: "getrpt.php", 
     type: "get", 
     data: data, 
     contentType: 'application/json; charset=utf-8', 
     async: true, 
     error: function(XMLHttpRequest, textStatus, errorThrown) { 
     console.log("error: "+textStatus+" : "+errorThrown); 
     } 
    }) 
    .done(function(response){ 
     var obj = jQuery.parseJSON(JSON.stringify(response)); 
     arrPONFail.push({Month: months[tMon-1]+"/"+tYear, PONFail: obj[0].PONFail}); 
     dt = new Date(dt.setMonth(parseInt(dt.getMonth()) - 1)); 
     pushPONFail(dt, ct); 
    }); 

} // pushing values such as ["May/2017", 0] 

$(function() { 
    var dt = new Date(); 
    pushPONFail(dt, 0); 

    console.log(arrPONFail); 
}); 

这些是完整的功能。当我console.log数组时,它出现在我的照片中。我无法提取数据。

当我将数组打印到控制台时,如下图所示。

如何从数组中返回值? 当我做一个arrT [0]时,我得到一个未定义的。

请指教。

enter image description here

+0

您是在.done()之外的控制台日志记录arrT。 done()完成后,您应该控制日志arrT,或者您可以在1000毫秒内调用timeout函数,然后记录arrT。你会看到不同之处。 – supritshah1289

回答

0

这很可能是一个异步的问题 - 你访问.done()功能arrT[0]之外?如果是这样,当你访问它时,数组中没有任何东西 - 它是空的。您所做的ajax请求需要一些时间(毫秒),并且只有在数据返回后,您的数组才有内容。要使用数组中的值,请尝试将使用该数组的代码放在.done()函数本身内。

+0

问题是,我使用回调系统来避免在ajax中输入async:false。如果我做async:false,则值被正确定义。在.done()之后,我做了一个console.log(arrT),并且我得到了我附加的图片,这意味着值就在那里,对吗?只有当我试图提取的价值,然后我有未定义的。 – rherry

+0

尝试'done()'函数内的console.logging。如果你在外面做,你会遇到异步问题,因为'done()'函数之外的所有代码都会最后运行。 –