簡體   English   中英

多個回調getJSON jquery的問題

[英]Issue with multiple callbacks getJSON jquery

我需要創建一些標記彈出窗口,以在地圖上顯示來自不同ajax請求的信息。 要進行第二次通話,我使用從第一次通話中獲得的用戶ID。 第二個呼叫的信息顯示很好,但是所有彈出窗口都顯示了相同的名稱,這是第一個呼叫的最后一項的原因,為什么會發生這種情況,有人可以幫我嗎? 提前謝謝了!!!。

$.getJSON('url', function (data) { // first call
      for (var i = 0; i < data.length; i++) {            
        var name= data[i].name;
        var location= data[i].location;
        var userID = data[i].userID;
        var myIcon= data[i].icon;   
        var marker = new L.Marker(location, {title: name, icon: myIcon});// create the marker           
        $.getJSON('https://api.site.com/data/'+userID+'',(function(marker){ // second call using userID
          return function(data2) {
          var info1 = data2.response.tips.items[0].text;
          var info2 = data2.response.tips.items[1].text;
          marker.bindPopup("<div class='popup'>" + name +"</br>"+ info1 +"</br>"+ info2 + "</div>", {maxWidth: '600'}) // create the popup and add it to the marker                     
                }
         })(marker)
        );
      shops.addLayer(marker); // add marker to map layer
      }

您需要在閉包中捕獲name ,就像對marker

    $("#loadingDiv").show();
    $.getJSON('https://api.site.com/data/'+userID+'',(function(marker, name){ // second call using userID
      return function(data2) {
      var info1 = data2.response.tips.items[0].text;
      var info2 = data2.response.tips.items[1].text;
      marker.bindPopup("<div class='popup'>" + name +"</br>"+ info1 +"</br>"+ info2 + "</div>", {maxWidth: '600'}) // create the popup and add it to the marker
      $("#loadingDiv").hide();                   
            }
     })(marker, name)

<div id="#loadingDiv" style="display: none">Loading...</div>

暫無
暫無

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

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