2012-03-28 71 views
3

你好,我打电话这个功能:从jQuery.post AJAX调用中返回数据?

function getCoordenadas() 
{ 
    var coordenadas = new Array(); 
    $.post(
     '<?=$this->baseUrl('user/parse-kml')?>', 
     { kmlName: "esta_chica.kml"}, 
     function(jsonCoord) { 
      jQuery.each(jsonCoord, function(i, val) { 
       var latlng = val.split(','); 
       coordenadas.push(new google.maps.LatLng(latlng[0], latlng[1])); 
      }); 
     }, 
     'json' 
    ); 
    return coordenadas; 
} 

这样的:

$(document).ready(function(){ 
    $('.caller').click(function() { 
     console.log(getCoordenadas()); 
    }); 
}); 

因此,当你点击它.caller调用函数得到正确的数据填充数组,但执行console.log( getCoordenadas());输出[]。

如果我从函数范围移动数组声明(var coordenadas = new Array();)以使其成为全局函数,当我第一次单击.caller时console.log(getCoordenadas());输出[],但第二次输出数组正确。有任何想法吗?

在此先感谢

+0

http://stackoverflow.com/questions/388436/jquery-ajax-return-value,http://stackoverflow.com/questions/2195161/how-to-return-an-array-from-jquery-ajax - 成功函数正确 – 2012-03-28 11:01:01

+0

可能重复[如何返回数据到原来的调用者函数在Javascript?](http://stackoverflow.com/questions/1094716/how-does-one-return-data-to-原始呼叫者功能在JavaScript) – 2012-03-28 11:01:36

回答

3

此功能以异步方式工作。 AJAX文章被触发,然后函数返回而无需等待AJAX​​调用完成。这就是为什么coordenadas数组是空的。

当你使它成为全局的,第一次它仍然是空的,第二次尝试时,ajax返回并填充数组。您应该重构您的代码以使用回调。事情是这样的:

// definition 
function getCoordenadas(callback) 
{ 
    var coordenadas = new Array(); 
    $.post(
     '<?=$this->baseUrl('user/parse-kml')?>', 
     { kmlName: "esta_chica.kml"}, 
     function(jsonCoord) { 
      jQuery.each(jsonCoord, function(i, val) { 
       var latlng = val.split(','); 
       coordenadas.push(new google.maps.LatLng(latlng[0], latlng[1])); 
      }); 
      callback(coordenadas); 
     }, 
     'json' 
    ); 
} 

// usage 
$(document).ready(function(){ 
    $('.caller').click(function() { 
     getCoordenadas(function(coord) { 
     console.log(coord); 
     }) 
    }); 
}); 
+0

Jajaja,我怀疑这一点。感谢您的确认! – lloiacono 2012-03-28 11:03:15

1

如果你需要一个完整的功能,您不能使用$.post功能;

您需要直接拨打$.ajax函数。 您传递一个可以具有“成功”,“错误”和“完整”回调的选项对象。

取而代之的是:

$.post(<?=$this->baseUrl('user/parse-kml')?>, parameters, function); 

你这样做:

$.ajax({ 
    url: <?=$this->baseUrl('user/parse-kml')?>, 
    type: "POST", 
    data: parameters, 
    success: successFunction, 
    error: errorFunction, 
    complete: completefunction 

}); 

有许多可用的过其他选项。 The documentation列出了所有可用的选项。

+0

谢谢,这个问题更适合我的需求 – lloiacono 2012-03-28 16:18:32