在异步请求期间难以将数据推送到数组

时间:2016-11-27 05:52:50

标签: javascript jquery ajax

在下面的代码中,我想知道为什么我的console.log(dataArray)显示一个空数组。我认为可以在ajax请求完成提取数据之前调用console.log。如果是这种情况,有没有办法在调用console.log之前等待ajax请求完成?

var dataArray = [];

var gdpAPI = "https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/GDP-data.json";
  $.getJSON( gdpAPI, {
    format: "json",
    async: false

  })
    .done(function( data ) {


    yearsData = data['data']


    $.each(yearsData, function(i){
       dataArray.push(yearsData[i]);


    })


 });

 console.log(dataArray);

提前谢谢你。 悦

2 个答案:

答案 0 :(得分:1)

异步代码

您在请求完成之前调用RelativeLayout.LayoutParams relParams = new RelativeLayout.LayoutParams( width, ViewGroup.LayoutParams.WRAP_CONTENT); yourRelativeLayout.setLayoutParams(relParams); 是正确的。只需将您的日志语句放在console.log部分内即可。

Working Fiddle



.done

var dataArray = [];

var gdpAPI = "https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/GDP-data.json";
$.getJSON(gdpAPI, {
    format: "json",
    async: false

  })
  .done(function(data) {


    yearsData = data['data']

    $.each(yearsData, function(i) {
      dataArray.push(yearsData[i]);


    })
		console.log('length: ' + dataArray.length,dataArray);

  });




答案 1 :(得分:1)

你必须使用回调函数从函数中获取数据并操纵sendMethedata是你的回调函数的数据



var dataArray = [];

var gdpAPI = "https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/GDP-data.json";
  $.getJSON( gdpAPI, {
    format: "json",
    async: true

  })
    .done(function( data ) {


   var yearsData = data['data']


    $.each(yearsData, function(i){
       dataArray.push(yearsData[i]);


    });
    sendMethedata(dataArray);

 });

function sendMethedata(data){
console.log(data)
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;