JSON响应中的JSON调用

JSON call inside JSON response.

本文关键字:JSON 调用 响应      更新时间:2023-11-15

我在另一个调用中有一个JSON API调用。这是因为loadJSON()需要来自第一个调用的动态数据(lat/lon值)。

因为数据是异步的,所以它似乎不能及时工作——所以控制台在控制台的末尾输出站名。

但是正确的站名称没有被注入到正确的站id(例如,站-4)。

非常感谢您的帮助。请注意,我正在寻找一个不依赖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();
}

您可以尝试成功,或者完成ajax方法,该方法在请求完成时运行(在成功和错误函数之后)。

像这样的东西。

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

没有JQuery的解决方案是这样的。

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");