简体   繁体   中英

JSON call inside JSON response.

I have a JSON API call inside another call. This is because loadJSON() needs the dynamic data (lat/lon values) from the first call.

Because the data is asynchronous it doesn't appear to work in time - so the console outputs the stations names at the end of the console.

But the correct station name is not injected to the correct station id (eg station-4).

Any help much appreciated. Please note, I am ideally looking for a solution that doesn't not rely on jQuery.

window.apiCallback = function(data) {

  for (i=0; i < 10; i++) {
    document.getElementById("title-"+i+"").innerHTML = data.results[i].name;
  }

  loadJSON('http://trainstationsdata/near.json?lat='+data.results[i].venue.lat+'&lon='+data.results[i].venue.lon+'&page=1&rpp=1',
    function(result) { 
        // this works and outputs at the end of console
        console.log(result.stations[0].name);

        // this doesn't work
        document.getElementById("station-"+i+"").innerHTML = result.[i].station_name;;
    },
    function(xhr) { console.error(xhr); }
  );

}

function loadJSON(path, success, error)
{
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function()
    {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status === 200) {
                if (success)
                    success(JSON.parse(xhr.responseText));
            } else {
                if (error)
                    error(xhr);
            }
        }
    };
    xhr.open("GET", path, true);
    xhr.send();
}

You can try with success, or complete ajax method, that runs when the request is finished (after success and error functions).

Something like this.

    function testAjax(handleData) {
  $.ajax({
    url:"getvalue.php",  
    complete:function(data) {
      handleData(data); 
    }
  });
}

and the solution without JQuery would be something like this.

var r = new XMLHttpRequest(); 
r.open("POST", "webservice", true);
r.onreadystatechange = function () {
    if (r.readyState != 4 || r.status != 200) return; 
    console.log(r.responseText);
};
r.send("a=1&b=2&c=3");

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