2012-08-26 60 views
0

我是OOP的新手,我嘗試使用ajax請求構建對象。我需要的是以JSON格式獲得'responseArray',而不是工作。使用AJAX設置對象屬性

function adres(adres) { 

this.adres_string = adres; 
var self = this 
$.ajax({ 
    type: 'POST', 
    url: "http://nominatim.openstreetmap.org/search?q="+adres+"&format=json&polygon=0&addressdetails=0", 
    success: function(data) { 
     self.responseArray = eval('(' + data + ')') 

    } 

}) 


//Method returning point coordinates in EPSG:4326 system 
this.getLonLat = function() { 

    var lonlat = new OpenLayers.LonLat(this.responseArray.lon, this.responseArray.lat); 
    return lonlat; 

} 
} 

問題開始時在appilcation代碼我寫:

var adr = new adres('Zimna 3, Warszawa'); 
adr.getLonLat(); 

這將返回毫無作爲,沒有及時得到來自服務器的響應。 如何正確寫入最佳方式?我讀過有關jQuery中的when()。then()方法的信息。這對我來說可能沒問題。我只是想知道最佳實踐

回答

1

這是AJAX的工作原理(注意A-同步部分)。您是對的,您撥打adr.getLonLat()的回覆尚未回覆。這是設計我建議:只通過回調函數參考adres構造:

function adres(adres, callbackFun) { 
    //... 
    success: function(data) { 
    var responseArray = eval('(' + data + ')') 
    var lonlat = new OpenLayers.LonLat(responseArray[i].lon, responseArray[i].lat); 
    callbackFun(lonlat) 
} 

,並調用它像這樣:

adres('Zimna 3, Warszawa', function(lonlat) { 
    //... 
}) 

幾句話:

  • adres現在基本上是一個函數,在這裏你不需要一個對象。

  • 不使用eval來解析JSON,使用JSON對象。

  • 您確定您可以發佈到http://nominatim.openstreetmap.org嗎?您可能會遇到相同的原產地政策問題

  • 其中是i變量來自responseArray[i]

+0

謝謝!我使用eval和'i',因爲這個代碼snipset只是從更大的部分提取。有可能會返回多個對象。我忘了刪除[我](只是編輯我的問題)。 Nominatim的ToS不是非常有限http://wiki.openstreetmap.org/wiki/Nominatim_usage_policy – Odoakr

+0

@Odoakr:由*同源策略*我的意思是[this](http://en.wikipedia.org/wiki/Same_origin_policy) ,沒有任何關於ToS或合法的東西。 –

+0

對不起,我沒有明白。這只是爲了測試。如果我決定編寫一個基於Nominatim的應用程序,我會在我的服務器上安裝這個實例。 – Odoakr