2012-10-17 68 views
1

我有這樣的代碼:

for(var i in dataJson){  
      direcc=dataJson[i].dir ; 
      id=dataJson[i].id ; 

    $.ajax({ 
      url: 'http://dev.virtualearth.net/REST/v1/Locations?query=' + direcc + '&key=mykey&jsonp=?', 
      dataType: 'json', 
     async: false, 
      success: function(result) { 

      loc = result.resourceSets[0].resources[0].point.coordinates; 
      direcc=result.resourceSets[0].resources[0].address.formattedAddress; 
      lat=loc[0]; 
      long=loc[1]; 


      $("#bing").append('latitudeBing:' + lat + '<p>longitudeBing:' + long+'$$$$$$'+id); 
} 
    }); 

的問題是,我想寫緯度+經度+ ID,但是當它寫的id是最後一個對所有的人(ID去從1-200,在所有座標出現200)。

最初的函數是$ getjson,我改變它使$ ajax調用async:false,但是這不能解決我的問題。

有人可以幫我嗎?非常感謝你!!

回答

1

編輯正確現在回答。

Fiddle to show the concept

for(var i in dataJson){  
    var direcc = dataJson[i].dir; 
    var id = dataJson[i].id; 
    makeAjaxCall(direcc, id); 
} 

function makeAjaxCall(direcc, id) { 
    $.ajax({ 
     url: 'http://dev.virtualearth.net/REST/v1/Locations?query=' + direcc + '&key=mykey&jsonp=?', 
     dataType: 'json', 
     async: false, 
     success: function(result) { 
      loc = result.resourceSets[0].resources[0].point.coordinates; 
      direcc=result.resourceSets[0].resources[0].address.formattedAddress; 
      lat=loc[0]; 
      long=loc[1]; 
      $("#bing").append('latitudeBing:' + lat + '<p>longitudeBing:' + long+'$$$$$$'+id); 
     } 
    }); 
} 

這使 「當前」 direccidmakeAjaxCall功能的範圍。我添加的小提琴只是顯示如何。

此外,無需保持async: false,左右,所以隨時刪除,如果你想。

+1

是的,這就是我想要做的。但是我已經在id的聲明中加了var,就像你說的,但它仍然不起作用 – Migua

+0

是的,你是對的。現在我再看一遍,它會不斷得到重置。我用一個可行的解決方案更新了我的答案。 – Gromer

+1

是的,它工作!他們沒有出現在順序..但我不cara因爲我需要的是座標和ID匹配,他們這樣做!非常感謝你!! – Migua