从jQuery.post AJAX调用返回的数据?数据、jQuery、post、AJAX

2023-09-10 19:35:04 作者:知心恋人

我调用这个函数:

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());输出[]。

So when you click .caller it calls the function gets the data correctly populates the array, but console.log(getCoordenadas()); outputs [].

如果我将数组声明(VAR coordenadas =新的Array();)从功能范围,使其成为全球性的,当我点击.caller首次执行console.log(getCoordenadas());输出[],但是第二次它正确输出的阵列。任何想法?

If I move the array declaration (var coordenadas = new Array();) from the function scope to make it global, when I click .caller for the first time console.log(getCoordenadas()); outputs [], but the second time it outputs the array correctly. Any ideas?

在此先感谢

推荐答案

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

This function works asynchronously. AJAX post is fired and then function returns without waiting for AJAX call to complete. That's why coordenadas array is empty.

当你把它全球性的,在第一时间它仍然是空的,被你尝试第二次,阿贾克斯返回并填充数组。你应该调整你的code使用回调。事情是这样的:

When you make it global, the first time it's still empty and by the second time you try, the ajax returned and populated the array. You should restructure your code to use a callback. Something like this:

// 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);
      })
    });
});