簡體   English   中英

jQuery AJAX 調用返回圖片順序錯誤-數據同步

[英]jQuery AJAX call returning images in wrong order - data synchronization

我使用 JQuery AJAX 調用返回給定城市(按緯度)的旅游景點的圖像、名稱、地址、國家和分數。 我將返回的數據保存到 5 arrays 中:用於圖像、名稱、地址、國家和分數。 Function "tom1"獲取除圖片以外的所有數據,觸發function "tom2"獲取圖片名稱。 Function “tom2” 觸發 function “callme”。

當 function call me 將所有 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);
    });
  }

}

是的,tom2 進行了一些異步調用,其中的回調 function 通常可以以不同的順序執行。 因此 imgId 中元素的順序將被混淆。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM