Jquery全局变量范围/错误值

时间:2014-04-01 08:02:33

标签: javascript jquery variables global

我的代码中的全局变量(success,count_error,error)的最终值存在问题。在输出部分之前,如果我不包括“警报(成功);”所有值都为零。但是,如果我包含该行,则输出正确的值。 为什么这样,变量范围有问题?

<html>
<head>

<script src="../jquery-1.11.0.js"></script>
<script>
var rows_all = [1,2,3,4,5,6,7,8,9,10],
    success = 0,
    count_error = 0,
    error = [];

/////////////////////////////////////////////////////////////////////////
// In test_addresses create lat/lon [number] from coordinates [string] //
/////////////////////////////////////////////////////////////////////////
$.getJSON("http://******.cartodb.com/api/v2/sql?q=" + "SELECT cartodb_id FROM test_addresses" + "&api_key=******", function(data) {

//get #rows for loop function
//$.each(data.rows, function(key, val) {
    //rows_all.push(val['cartodb_id']);
//});


//loop through rows (get coordinates), manipulate + post values
$.each(rows_all, function(key1, val1) {
    $.getJSON("http://******.cartodb.com/api/v2/sql?q=" + "SELECT address, coordinates FROM test_addresses WHERE cartodb_id=" + val1 + "&api_key=******", function(data1) {
        $.each(data1.rows, function(key2, val2) {
            address = val2['address'];
            lat_lon = val2['coordinates'];
            if (lat_lon.indexOf('?') === -1) {
                lat = parseFloat( lat_lon.split(',')[0] );
                lon = parseFloat( lat_lon.split(',')[1] );
                $.post("http://******.cartodb.com/api/v2/sql?q=" + "UPDATE test_addresses SET lat=" + lat + ", lon=" + lon + "WHERE cartodb_id=" + val1 + "&api_key=******");
                success++; //number of successfully completed operations
            }
            else {
                count_error++; //#error operations
                list = {};
                list["id"] = val1; //@which cartodb_id in table
                list["address"] = address; //@which matching address in table
                error.push(list); 
            }
        });
    });
});

alert( success );
//Ouput text    
$("#result").html(success + " entries successfully geocoded. </br><br>There were " + count_error + " errors. <br>More pecifically at cartodb_id : address:");   
$.each(error, function(key4, val4) {
    $("#result").append("<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + val4["id"] + " : " + val4["address"]);
});

$.each(rows_all, function(key5, val5) {
    $("#result").append("<br>" + key5);
});
});

</script>
</head>

<body>
    <p id="result"></p>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

这是一个异步请求,因此alert()会在获取数据之前触发。所以你应该改变代码,

$.getJSON("http://******.cartodb.com/api/v2/sql?q=" + "SELECT cartodb_id FROM test_addresses" + "&api_key=******", function (data) {

//get #rows for loop function
//$.each(data.rows, function(key, val) {
//rows_all.push(val['cartodb_id']);
//});


//loop through rows (get coordinates), manipulate + post values
$.each(rows_all, function (key1, val1) {
    $.getJSON("http://******.cartodb.com/api/v2/sql?q=" + "SELECT address, coordinates FROM test_addresses WHERE cartodb_id=" + val1 + "&api_key=******", function (data1) {
        $.each(data1.rows, function (key2, val2) {
            address = val2['address'];
            lat_lon = val2['coordinates'];
            if (lat_lon.indexOf('?') === -1) {
                lat = parseFloat(lat_lon.split(',')[0]);
                lon = parseFloat(lat_lon.split(',')[1]);
                $.post("http://******.cartodb.com/api/v2/sql?q=" + "UPDATE test_addresses SET lat=" + lat + ", lon=" + lon + "WHERE cartodb_id=" + val1 + "&api_key=******");
                success++; //number of successfully completed operations
                alert(success);

            } else {
                count_error++; //#error operations
                list = {};
                list["id"] = val1; //@which cartodb_id in table
                list["address"] = address; //@which matching address in table
                error.push(list);
            }
        });
        //Ouput text    
        $("#result").html(success + " entries successfully geocoded. </br><br>There were " + count_error + " errors. <br>More pecifically at cartodb_id : address:");
        $.each(error, function (key4, val4) {
            $("#result").append("<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + val4["id"] + " : " + val4["address"]);
        });

        $.each(rows_all, function (key5, val5) {
            $("#result").append("<br>" + key5);
        });
    });
});



});

您应该将代码置于$.getJSON范围内。所以只有在获取数据后它才会运行。

实际上它没有警觉()做魔术。如果您发出警报,则成功事件将在用户单击“确定”按钮之前的较短时间内发生。在这段时间内,将填充所有值。