2012-03-28 73 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