2013-06-28 72 views
0

我需要創建一些標記彈出窗口,顯示來自地圖上不同ajax請求的信息。爲了進行第二次呼叫,我使用了我從第一次呼叫中獲得的用戶ID。來自第二個電話的信息表明它很好,但是所有彈出窗口都顯示了相同的名稱,第一個電話的最後一個項目,爲什麼發生這種情況,有誰能幫助我嗎?提前謝謝了!!!。多個回調問題getJSON jquery

$.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 
     } 
+0

您必須從'marker'獲取'name'或將'name'添加到閉包中的變量中。 – Barmar

+0

對不起@Barmar,你能解釋一下嗎?謝謝!! – Pela

+0

我以爲你會明白,因爲你已經爲'marker'做過這個。我發佈了一個顯示它的答案。 – Barmar

回答

0

您需要捕獲name在封閉,就像你做。

$("#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>