$ .getJSON回调未按预期设置全局变量

时间:2015-11-19 14:00:34

标签: javascript callback global-variables getjson

情况

我使用$.getJSON调用API,并希望设置一些全局变量。我跟着this example here并成功运行了回调函数。当我console.log我想要的全局变量woodmontTotalwoodmontAvailable时,如果在回调函数中运行console.log,我可以看到它们。但是,在回调函数之外,全局变量是未定义的。

我的理解是使用$.getJSON中的值定义全局变量,回调函数将设置全局变量。

我的最终目标是在地图上的信息窗口中显示变量woodmontTotal和WoodmontAvailable。

问题

  1. 如何将全局变量woodmontTotal设置为object[i].total_spaces等于object[i].facilitynumber = "GAR 57'
  2. 如何将变量woodmontAvailable设置为object[i].space_count object[i].facilitynumber = "GAR 57'
  3. 在上面的例子中,为什么这解决了问题,而我的回调函数没有设置全局变量?有什么区别,如果有的话?
  4. 回调函数

    //call the data back
    function getGarageCount(callback) {
        var name = "default";
        $.getJSON(url, function(entry) {
            name = entry;
            callback(name);
        });
    };
    getGarageCount(function(value) {
        $.each(value, function(i, field) {
            if (value[i].facilitynumber === "GAR 31") {
                woodmontTotal = value[i].total_spaces;
                woodmontAvailable = value[i].space_count;
            };
        });
        console.log(woodmontTotal);
        console.log(woodmontAvailable);
    });
    //set markers
    markers = [
        ["4841 Bethesda Avenue (Elm Street)", 38.980724, -77.0964, bethesdaTotal,
            bethesdaAvailable
        ],
        ["7171 Woodmont Avenue", 38.980097, -77.093662, woodmontTotal,
            woodmontAvailable
        ],
        ["921 Wayne Avenue", 38.995740, -77.025652, wayneTotal, wayneAvailable],
        ["801 Ellsworth Drive", 38.997778, -77.025071, ellsworthTotal,
            ellsworthAvailable
        ]
    ];
    

    Fiddle here.

    HTML:

    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script src="http://maps.googleapis.com/maps/api/js"></script>
    </head>
    <body>
        <h1 style="text-align: center;">Parking Garage Availability</h1>
    
        <div id="map"></div>
    
        <ul id="list"></ul>
        <p id="GAR57"></p>
        <p id="GAR31"></p>
        <p id="GAR60"></p>
        <p id="GAR61"></p>
    </body>
    

    CSS:

    #map {
        height: 300px;
        width: 500px;
        margin: 0 auto;
        border: 1px solid black;
    }
    

    JavaScript的:

    var map;
    var mapProp;
    var marker;
    var markers;
    var url;
    var myData;
    var time;
    var available;
    var total;
    var facility;
    var position;
    var infoWindow;
    var bethesdaTotal;
    var bethesdaAvailable;
    var woodmontTotal;
    var woodmontAvailable;
    var wayneTotal;
    var wayneAvailable;
    var ellsworthTotal;
    var ellsworthAvailable;
    
    function initialize() {
        mapProp = {
            center: new google.maps.LatLng(38.994890, -77.063416),
            zoom: 9,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById("map"), mapProp);
        // Try HTML5 geolocation.
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
                var pos = {
                    lat: position.coords.latitude,
                    lng: position.coords.longitude
                };
                infoWindow.setPosition(pos);
                infoWindow.setContent('Location found.');
                map.setCenter(pos);
            }, function() {
                handleLocationError(true, infoWindow, map.getCenter());
            });
        } else {
            // Browser doesn't support Geolocation
            handleLocationError(false, infoWindow, map.getCenter());
        }
    }
    
    function handleLocationError(browserHasGeolocation, infoWindow, pos) {
        infoWindow.setPosition(pos);
        infoWindow.setContent(browserHasGeolocation ? 'Error: The Geolocation service failed.' :
            'Error: Your browser doesn\'t support geolocation.');
    }
    $(document).ready(function() {
        initialize();
        url = 'https://data.montgomerycountymd.gov/resource/qahs-fevu.json';
        $.getJSON(url, function(data) {
            myData = data;
            for (i = 0; i < myData.length; i++) {
                time = (myData[i].asofdatetime).slice(11);
                available = myData[i].space_count;
                total = myData[i].total_spaces;
                facility = myData[i].facilitynumber;
                //get names
                if (facility === "GAR 57") {
                    facility = "4841 Bethesda Avenue (Elm Street)";
                    $('#GAR57').html('As of ' + time + ' there are ' + available +
                        ' of ' + total + ' at ' + facility);
                } else if (facility === "GAR 31") {
                    facility = "7171 Woodmont Avenue";
                    $('#GAR31').html('As of ' + time + ' there are ' + available +
                        ' of ' + total + ' at ' + facility);
                } else if (facility === "GAR 60") {
                    facility = "921 Wayne Avenue";
                    $('#GAR60').html('As of ' + time + ' there are ' + available +
                        ' of ' + total + ' at ' + facility);
                } else {
                    facility = "801 Ellsworth Drive";
                    $('#GAR61').html('As of ' + time + ' there are ' + available +
                        ' of ' + total + ' at ' + facility);
                }
            }
        });
        //call the data back
        function getGarageCount(callback) {
            var name = "default";
            $.getJSON(url, function(entry) {
                name = entry;
                callback(name);
            });
        };
        getGarageCount(function(value) {
            $.each(value, function(i, field) {
                if (value[i].facilitynumber === "GAR 31") {
                    woodmontTotal = value[i].total_spaces;
                    woodmontAvailable = value[i].space_count;
                };
            });
            console.log(woodmontTotal);
            console.log(woodmontAvailable);
        });
        //set markers
        markers = [
            ["4841 Bethesda Avenue (Elm Street)", 38.980724, -77.0964, bethesdaTotal,
                bethesdaAvailable
            ],
            ["7171 Woodmont Avenue", 38.980097, -77.093662, woodmontTotal,
                woodmontAvailable
            ],
            ["921 Wayne Avenue", 38.995740, -77.025652, wayneTotal, wayneAvailable],
            ["801 Ellsworth Drive", 38.997778, -77.025071, ellsworthTotal,
                ellsworthAvailable
            ]
        ];
        console.log(markers)
        infoWindow = new google.maps.InfoWindow();
        for (var i = 0; i < markers.length; i++) {
            position = new google.maps.LatLng(markers[i][1], markers[i][2]);
            marker = new google.maps.Marker({
                position: position,
                animation: google.maps.Animation.DROP,
                map: map,
                title: markers[i][0]
            });
            google.maps.event.addListener(marker, 'click', (function(marker, i) {
                return function() {
                    infoWindow.setContent("<div>" + markers[i][0] + "</div>");
                    infoWindow.open(map, this);
                };
            })(marker, i));
        };
    });
    

0 个答案:

没有答案