【问题标题】:jQuery AJAX call returning images in wrong order - data synchronizationjQuery AJAX 调用以错误的顺序返回图像 - 数据同步
【发布时间】:2020-09-22 03:52:12
【问题描述】:

我使用 JQuery AJAX 调用返回给定城市(按纬度)中旅游景点的图像、名称、地址、国家和分数。我将返回的数据保存到 5 个数组中:图像、姓名、地址、国家和分数。 函数“tom1”获取除图像之外的所有数据,它触发函数“tom2”获取图像名称。 函数“tom2”触发函数“callme”。

当函数调用我将所有 5 个值附加到页面时,图像通常与其他信息不匹配。

和AJAX的异步请求有关系吗?

你能帮我解决吗?这是我的代码:

function tom1(lat, lon) {
  var queryURL = "https://api.tomtom.com/search/2/search/museum.json?key=" + tomAPI + "&lat=" + lat + "&lon=" + lon;

  $.ajax({
    url: queryURL,
    method: "GET"
  }).then(function(response) {

    //only select POIs which possess "dataSources" key = images
    for (var i = 0; i < 20; i++) {
      if (response.results[i].dataSources !== undefined) {
        poiId.push(response.results[i].dataSources.poiDetails[0].id);
        placeName.push(response.results[i].poi.name);
        address.push(response.results[i].address.freeformAddress);
        country.push(response.results[i].address.country);
        rank.push(response.results[i].score.toFixed(1));
      } else {
        console.log("not lucky today")
      }
    }
    tom2(poiId);
  });
}

// get POI details and images after you know POI's ID
function tom2(poiId) {

  for (i = 0; i < poiId.length; i++) {
    var queryURL = "https://api.tomtom.com/search/2/poiDetails.json?key=" + tomAPI + "&id=" + poiId[i];

    $.ajax({
      url: queryURL,
      method: "GET"
    }).then(function(response) {
      imgId.push(response.result.photos[0].id);
      callme(imgId);
    });
  }

}

【问题讨论】:

标签: javascript jquery ajax api asynchronous


【解决方案1】:

是的,tom2 进行了许多异步调用,并且这些回调函数通常可以以不同的顺序执行。所以imgId中元素的顺序会混淆。

【讨论】:

    猜你喜欢
    • 2013-03-15
    • 2015-07-15
    • 2012-10-28
    • 1970-01-01
    • 2018-03-05
    • 1970-01-01
    • 2016-09-17
    • 1970-01-01
    • 2016-01-07
    相关资源
    最近更新 更多