使用 jquery 加载数据后使用 json 数据

Using json data after loading it using jquery

因此,我尝试加载一个 json 文件,该文件具有 header 和使用 Javascript 的数据属性,然后尝试在其他方法中使用该数据。 json 文件加载得很好(由 "console.log(header.dx)" 证明),但代码没有更新我的外部数组(由对 "console.log(productPoints.length, productPoints)" 的调用证明)。我做错了什么?

var productFile = "aJsonFile.json";
var productPoints = [];
$.getJSON(productFile)
  .done(function(json) {
    var data = json[0].data;
    var header = json[0].header;
    console.log(header.dx);
    k = 0;
    for (var j = 0; j < header.ny; j++) {
      for (var i = 0; i < header.nx; i++, k++) {
        var point = new ol.geom.Point(
          [floorMod(180 + header.lo1 + i * header.dx, 360) - 180, 
          header.la1 - j * header.dy]
        );
        var feature = new ol.Feature({ geometry: point, value: data[k] });
        productPoints.push(feature);
      } 
    }
  });
console.log(productPoints.length, productPoints);

var floorMod = function(a, n) {
  var f = a - n * Math.floor(a / n);
  return f === n ? 0 : f;
};

Ajax 调用是异步的。 ajax 调用可能会在您记录数组后结束。尝试将 console.log 移动到 done() 函数中。

var productFile = "aJsonFile.json";
var productPoints = [];
$.getJSON(productFile)
  .done(function(json) {
    var data = json[0].data;
    var header = json[0].header;
    console.log(header.dx);
    k = 0;
    for (var j = 0; j < header.ny; j++) {
      for (var i = 0; i < header.nx; i++, k++) {
        var point = new ol.geom.Point(
          [floorMod(180 + header.lo1 + i * header.dx, 360) - 180, 
          header.la1 - j * header.dy]
        );
        var feature = new ol.Feature({ geometry: point, value: data[k] });
        productPoints.push(feature);
      } 
    }
    console.log(productPoints.length, productPoints);
  });


var floorMod = function(a, n) {
  var f = a - n * Math.floor(a / n);
  return f === n ? 0 : f;
};