2012-08-26 58 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