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

12 浏览
0 Comments

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

嗨,我正在调用这个函数:

function getCoordenadas()
{
    var coordenadas = new Array();
    $.post(
        '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
0 Comments

问题的原因是函数是异步执行的,即在发出 AJAX 请求后立即返回,不等待 AJAX 请求完成。所以,在函数返回之前,coordenadas 数组为空。

当将其定义为全局变量时,第一次仍然为空,但在第二次尝试时,AJAX 已经返回并填充了数组。你应该重新组织代码以使用回调函数。类似这样:

// 定义
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'
    );  
}
// 使用
$(document).ready(function(){
    $('.caller').click(function() {
      getCoordenadas(function(coord) {
        console.log(coord);
      })
    });
});

哈哈哈,我怀疑是这样的。谢谢你的确认!

0
0 Comments

问题的原因是需要一个完整的函数,而不能使用$.post函数。解决方法是直接调用$.ajax函数,并传递一个包含"success"、"error"和"complete"回调函数的选项对象。代码示例中的$.post函数被替换为$.ajax函数,同时加入了指定的选项。另外,文档中还列出了其他可用的选项。

0