Ajax没有调用成功函数

时间:2018-06-20 11:54:26

标签: javascript ajax google-maps

我正在尝试创建一个谷歌地图。我编写了一个GET类型的REST服务,该服务以json格式提供数据,我正在JS中使用ajax对其进行调用。当我在浏览器中点击该REST服务时,我得到了数据,但是当我尝试使用ajax来获得数据时,它不起作用。我无法理解我在这里做错了什么。我只需单击一下按钮即可创建这些数据的标记。

因此,我尝试将REST服务输出(json)放入变量中,代码工作正常。单击按钮即可创建标记。但是,当我调用“ getMapData()”以获取数据并单击按钮时,在这种情况下代码无法正常工作。我真的无法理解第二种情况。

这是键盘输入法的链接-https://codepen.io/pinkisharma/pen/XYZGgN

<!DOCTYPE html>
<html>

<head>
    <title>Geocoding service</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
        /* Always set the map height explicitly to define the size of the div
               * element that contains the map. */

        #map {
            height: 100%;
        }

        /* Optional: Makes the sample page fill the window. */

        html,
        body {
            height: 100%;
            margin: 0;
            padding: 0;
        }

        #floating-panel {
            position: absolute;
            top: 10px;
            left: 25%;
            z-index: 5;
            background-color: #fff;
            padding: 5px;
            border: 1px solid #999;
            text-align: center;
            font-family: 'Roboto', 'sans-serif';
            line-height: 30px;
            padding-left: 10px;
        }
    </style>
</head>
<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY">
</script>

<body>
    <div id="floating-panel">
        <input id="address" type="textbox" value="Sydney, NSW">
        <input id="submit" type="button" value="Geocode">
    </div>
    <div id="map"></div>
    <script>
        popupJson = "";
        RoomTypeData = [{
            'roomType': 'CA'
        }, {
            'roomType': 'HGg'
        }, {
            'roomType': 'yertf'
        }, ];
        var tomcatServerIp = "localhost";
        var tomcatPort = "8180"
        //providing map options for map creation


        //for storage of markers
        markersArr = [];
        mapDatset = [{
            "sitename": "ZONA RESTRINGIDA",
            "clientname": "Interserve Spain",
            "zipcode": "7611",
            "isActive": "active",
            "latitude": "0",
            "longitude": "0",
            "activeEmp": 5,
            "activeDevices": 5,
            "siteAdress": "Palma de Mallorca,7611"
        }, {
            "sitename": "BANCA MARCH O.P",
            "clientname": "Interserve Spain",
            "zipcode": "7040",
            "isActive": "active",
            "latitude": "0",
            "longitude": "0",
            "activeEmp": 14,
            "activeDevices": 5,
            "siteAdress": "Avenida Alejandro Rosello 8,7040"
        }, {
            "sitename": "ZONA TIERRA",
            "clientname": "Interserve Spain",
            "zipcode": "7611",
            "isActive": "active",
            "latitude": "0",
            "longitude": "0",
            "activeEmp": 6,
            "activeDevices": 5,
            "siteAdress": "Palma de Mallorca,7611"
        }, {
            "sitename": "TERMINAL D Y B",
            "clientname": "Interserve Spain",
            "zipcode": "7611",
            "isActive": "active",
            "latitude": "0",
            "longitude": "0",
            "activeEmp": 4,
            "activeDevices": 5,
            "siteAdress": "Palma de Mallorca,7611"
        }, {
            "sitename": "TERMINAL A",
            "clientname": "Interserve Spain",
            "zipcode": "7611",
            "isActive": "active",
            "latitude": "0",
            "longitude": "0",
            "activeEmp": 7,
            "activeDevices": 5,
            "siteAdress": "Palma de Mallorca,7611"
        }, {
            "sitename": "TERMINAL C",
            "clientname": "Interserve Spain",
            "zipcode": "7611",
            "isActive": "active",
            "latitude": "0",
            "longitude": "0",
            "activeEmp": 4,
            "activeDevices": 5,
            "siteAdress": "Palma de Mallorca,7611"
        }, {
            "sitename": "NAVE AENA IV",
            "clientname": "Interserve Spain",
            "zipcode": "7611",
            "isActive": "inactive",
            "latitude": "0",
            "longitude": "0",
            "activeEmp": 4,
            "activeDevices": 5,
            "siteAdress": "Palma de Mallorca,7611"
        }, {
            "sitename": "BANCA MARCH SON PERETO",
            "clientname": "Interserve Spain",
            "zipcode": "7013",
            "isActive": "inactive",
            "latitude": "0",
            "longitude": "0",
            "activeEmp": 1,
            "activeDevices": 5,
            "siteAdress": "C/ Bartolome Sureda I misserol,7013"
        }];

        initMap();

        function initMap() {

            var mapOptions = {
                zoom: 2,
                cursor: 'crosshair',
                center: new google.maps.LatLng(37.428432, -122.127379),
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };

            map = new google.maps.Map(document.getElementById('map'), mapOptions);
            var geocoder = new google.maps.Geocoder();

            document.getElementById('submit').addEventListener('click', function() {
                //     getMapData();
                for (i = 0; i < mapDatset.length; i++) {
                    geocodeAddressAndSetMarker(geocoder, map, mapDatset[i]);
                }
            });
        }


        //getMapData();
        function getMapData() {
            $.ajax({
                url: "http://127.0.0.1:8180/services/restService/GetSitesData?clientname=" + "Interserve Spain",
                type: "GET",
                async: true,
                success: function(json) {
                    mapDatset = json;
                    console.log("mapdata Json Length :" + mapDatset.length);
                    console.log("Received json :" + JSON.stringify(mapDatset));
                },
                error: function() {
                    console.log("some error occured in fetching data");
                    mapDatset = [];
                }
            });
        }

        function geocodeAddressAndSetMarker(geocoder, resultsMap, info) {

            var address = info.zipcode;
            geocoder.geocode({
                'address': address
            }, function(results, status) {
                if (status === 'OK') {
                    var loc = results[0].geometry.location;
                    map.setZoom(5);
                    resultsMap.setCenter(results[0].geometry.location);
                    var marker = new google.maps.Marker({
                        map: resultsMap,
                        position: results[0].geometry.location,
                        sitename: info.sitename,
                        //  icon: iconImage,
                        activeEmp: info.activeEmp,
                        activeDevice: info.activeDevices,
                        siteaddr: info.siteAdress,
                        isActive: info.isActive
                    });
                    var infowindow = new google.maps.InfoWindow({});
                    var iwContent = "";
                    if (marker.isActive === "active") {
                        // Creating the content to be inserted in the infowindow
                        iwContent = '<div id="iw_container">' + '<div class="iw_title" style="color:#32CD32;">Site Name : ' + marker.sitename + '</div>' + '<div class="iw_title" style="color:#32CD32;">Site Address : ' + marker.siteaddr + '</div>' + '<div style="color:#32CD32;float:left;padding-right:4px;" class="iw_title">Active Employees : ' + marker.activeEmp + '<div style="color:#32CD32;" class="iw_title">Active Devices : ' + marker.activeDevice + '</div></div>';
                    } else {
                        iwContent = '<div id="iw_container">' + '<div class="iw_title" style="color:#FF0000;">Site Name : ' + marker.sitename + '</div>' + '<div style="color:#FF0000;" class="iw_title">Site Address : ' + marker.siteaddr + '</div>' + '<div style="color:#FF0000;" class="iw_title">Active Employees : ' + marker.activeEmp + '</div>' + '<div style="color:#FF0000;" class="iw_title">Active Devices : ' + marker.activeDevice + '</div></div>';

                    }
                    //opening info window on mouseover
                    google.maps.event.addListener(marker, 'mouseover', (function(marker, iwContent, infowindow) {
                        return function() {
                            // including content to the Info Window.
                            infowindow.setContent(iwContent);
                            // opening the Info Window in the current map and at the current marker location.
                            infowindow.open(map, marker);
                        };
                    })(marker, iwContent, infowindow));

                    // on mouseout (moved mouse off marker) make infoWindow disappear
                    google.maps.event.addListener(marker, 'mouseout', (function(marker, iwContent, infowindow) {
                        return function() {
                            // closing the Info Window in the current map and at the current marker location.
                            infowindow.close();
                        };
                    })(marker, iwContent, infowindow));
                    markersArr.push(marker);
                } else {
                    alert('Geocode was not successful for the following reason: ' + status);
                }
            });
        }
    </script>
</body>

</html>

2 个答案:

答案 0 :(得分:0)

您的代码未调用

getMapData ... 取消注释getMapData,您将能够正确看到错误和成功回调

答案 1 :(得分:0)

要调试问题所在,可以按如下所示使用错误函数的其他参数。这将使您更容易研究实际问题。

$.ajax({
            url: "http://127.0.0.1:8180/services/restService/GetSitesData?clientname=" + "Interserve Spain",
            type: "GET",
            async: true,
            success: function(json) {
                mapDatset = json;
                console.log("mapdata Json Length :" + mapDatset.length);
                console.log("Received json :" + JSON.stringify(mapDatset));
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log('jqXHR:');
                console.log(jqXHR);
                console.log('textStatus:');
                console.log(textStatus);
                console.log('errorThrown:');
                console.log(errorThrown);
            }
        });