简体   繁体   中英

Javascript Callback Within a Callback

I am a stuck as to why I never hit the GETNEARCALLBACK function below. The logic goes something like this:

  1. On Page Load I call INITIALIZE
  2. INITIALIZE happily executes and calls GETSTATIONS
  3. GETSTATIONS does an AJAX request using GETNEARESTSTAIONS as the callback function, and the web server responds with the results of a database query in JSON format.
  4. GETNEARESTSTAIONS takes the results and creates a Google Maps API distance matrix request using GETNEARCALLBACK as the callback function
  5. I run my site and use Firebug to determine that I never get to GETNEARCALLBACK .

I think my use of Google Maps API is correct because if I don't call GETNEARESTSTATIONS from within my AJAX request, it executes properly.

function INITIALIZE() { GETPOSITION(); DRAWMAP(); GETADDR(); GETSTATIONS(); }

var xmlhttp;

function GETSTATIONS() {
  if(window.XMLHttpRequest) {
    xmlhttp = new XMLHttpRequest();
  } else {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange = GETNEARESTSTATION();
  xmlhttp.open("GET", "final.php", true);
  xmlhttp.send();
}

var STATIONLIST;

function GETNEARESTSTATION() {
  if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    STATIONLIST = eval("(" + xmlhttp.responseText + ")");
    var LAT = parseFloat(document.getElementById("LATITUDE").value);
    var LON = parseFloat(document.getElementById("LONGITUDE").value);
    var latlng = new google.maps.LatLng(LAT, LON);
    var destinationA = STATIONLIST[0].ADDRESS;
    var service = new google.maps.DistanceMatrixService();
    service.getDistanceMatrix({
      origins: [latlng],
      destinations: [destinationA],
      travelMode: google.maps.TravelMode.DRIVING,
      unitSystem: google.maps.UnitSystem.IMPERIAL,
      avoidHighways: false,
      avoidTolls: false
    }, GETNEARCALLBACK);
  }
}

function GETNEARCALLBACK(response, status) {
  if(status == google.maps.DistanceMatrixStatus.OK) {
    var destinations = response.destinationAddresses;
    var results = response.rows[0].elements;
    for(var j = 0; j < results.length; j++) {
      var element = results[j];
      document.getElementById("STATIONADDR").innerHTML = parseFloat(element.distance.value) + " " + response.destinationAddresses[j];
    }
  }
}

need function variables, rather than function return values

//xmlhttp.onreadystatechange = GETNEARESTSTATION(); //error
xmlhttp.onreadystatechange = GETNEARESTSTATION; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM