0

我想创建一个 JavaScript 全局变量,其中包含我需要的一些值。我从 XML 文件中读取了一些值并将其用于显示 Google Map 的地图。我会将这些信息存储在一些变量中,并在用户要求时显示它们。

我有这个代码:

var tot_pts = new Array(); //global variable

if (GBrowserIsCompatible()) { 

  // Display the map, with some controls and set the initial location 
  ...

  // A function to create the marker and set up the event window
  function createMarker(point,train) {
    var marker = new GMarker(point);
    return marker;
  }

  request.open("GET", "example.xml", true);
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      var xmlDoc = GXml.parse(request.responseText);
      //read value on XML
      tot_pts.push(new_path);

      //show all value on map
      for (var i = 0; i < tot_pts.length; i++) {
        point= [];
        point[0]=tot_pts[i].start;
        point[1]=tot_pts[i].end;
        map.addOverlay(new GPolyline(point,tot_pts[i].colour,3));
        marker = createMarker(tot_pts[i].start,tot_pts[i].train);
        map.addOverlay(marker);
        marker = createMarker(tot_pts[i].end,tot_pts[i].train);
        map.addOverlay(marker);
      }
    }//end of if request=4
  }// end of on ready...

  request.send(null);

}// end of compatible browser   

如果我将最后一个“for 循环”移到此代码中的另一个位置,则数组tot_pts为空。为什么会这样?我可以以某种方式改进我的代码吗?

4

1 回答 1

0

request.readyState == 4 表示 XMLHttpRequest 的响应已准备好。因此,当您收到响应时,您的数组 tot_pts 在 step -> tot_pts.push(new_path); 处被推送了一些值(new_path);在那之前,数组将显示为空,因为它没有明确设置值。

于 2013-03-15T13:33:16.410 回答