javascript - 信息窗口中的 AJAX 调用 : Scope Issue

标签 javascript ajax google-maps google-maps-api-3

或者至少我认为这是一个范围问题,如果我错了请纠正我。

我有一个 for 循环可以在我的 map 上生成标记。每个信息窗口使用对 ajax 函数的回调加载不同的内容。

我已简化此示例以概述问题。

var xhr = "";
var infowindow = new google.maps.InfoWindow();
var marker, i;
var polylineCoordinates = [new google.maps.LatLng(78.782762, 17.917843),
                           new google.maps.LatLng(-0.829439, -91.112473),
                           new google.maps.LatLng(15.066156, -23.621399),
                          ]


function createHttpRequest() {
    try {   
        xhr = new XMLHttpRequest();
        return xhr;
        }
        catch (e)
        {
            //assume IE6
            try {
            xhr = new activeXBbject("microsoft.XMLHTTP");
            return xhr;
            }
            catch (e)   {
                return alert("Unable to create an XMLHttpRequest object");
            }
        }
}



  function initialize() {

    var mapOptions = {
      center: new google.maps.LatLng(78.782762,17.917843),
      zoom: 10,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
        map = new google.maps.Map(document.getElementById("map_canvas"),
        mapOptions);
  }



//I recreated the polylineCoordinates array (see above)
//to try and replicate and real array in the script

for (i = 0; i < polylineCoordinates.length; i++) {
    marker = new google.maps.Marker({
        position: polylineCoordinates[i],
        map: map
    });

    google.maps.event.addListener(marker, 'click', (function (marker, i) {
        return function () {
            infowindow.setContent("<div id=\"infowindow\">" + getStationInfo(infoWindowDiv) + "</div>");
            infowindow.open(map, marker);

        }
    })(marker, i));

} //End adding markers loop


            function infoWindowDiv(stationInfo) {
                var add = document.createTextNode(stationInfo);
                document.getElementById("infowindow").appendChild(add);
            }


            function getStationInfo(callback) {
                //createHttpRequest() exists globally
                var xhr = createHttpRequest();
                var url = "stations.php" //edited out the original URL
                xhr.onreadystatechange = function () {
                    if (xhr.readyState == 4 && xhr.status == 200) {
                        var stationInfo = "This is a Test";
                        return callback(stationInfo)
                    } //end readyState

                } //end readystatechange
                xhr.open("GET", url, true);
                xhr.send(null);
            } //end getStationInfo

小修改:将函数移出循环

编辑 2: ajax 调用没有任何问题,为示例代码编辑了 url。请注意,最终输出在信息窗口中显示“This is a test”,这清楚地表明执行了成功的回调。此外,请注意没有 responseText 或 responseXml。返回的变量与url无关

回调工作正常,但由于某种原因,它上面有可怕的“未定义”。
控制台什么都不显示。
输出:

undefined
This is a test

我做错了什么?如果它有效,它怎么会是未定义的?

最佳答案

发生了什么:

  1. 你点击信息窗口
  2. 调用 getStationInfo(infoWindowDiv),触发 AJAX 请求,但没有返回任何有用信息(“未定义”,没有返回语句)
  3. AJAX 函数将遇到错误(url“此时不需要”不会导致 onreadystatechange 函数触发)。但你告诉我们这不是问题。
  4. 脚本遇到 javascript 错误 Uncaught TypeError: Cannot call method 'appendChild' of null 因为 ID 为 infowindow 的 div 尚未附加到 DOM。

建议在 infowindow 上添加一个事件监听器,以便在呈现 id="infowindow"之前不尝试访问 div(domready)。

工作代码:

    var xhr = "";
    var infowindow = new google.maps.InfoWindow();
    var map = null;
    var marker, i;
    var polylineCoordinates = [new google.maps.LatLng(78.782762, 17.917843),
                               new google.maps.LatLng(-0.829439, -91.112473),
                               new google.maps.LatLng(15.066156, -23.621399)
                              ]


      function initialize() {
        var mapOptions = {
          center: new google.maps.LatLng(78.782762,17.917843),
          zoom: 10,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
            map = new google.maps.Map(document.getElementById("map_canvas"),
            mapOptions);

    for (i = 0; i < polylineCoordinates.length; i++) {
        marker = new google.maps.Marker({
            position: polylineCoordinates[i],
            map: map
        });

        google.maps.event.addListener(marker, 'click', (function (marker, i) {
            return function () {
                infowindow.setContent("<div id=\"infowindow\" style=\"height:50px;width:200px;\"></div>");
                infowindow.open(map, marker);
            google.maps.event.addListenerOnce(infowindow,"domready", function(){
                  getStationInfo(infoWindowDiv);
                });
        })(marker, i));

    } //End adding markers loop

    }
            function infoWindowDiv(stationInfo) {
                var add = document.createTextNode(stationInfo);
                document.getElementById("infowindow").appendChild(add);
            }


            function getStationInfo(callback) {
                var stationInfo = "This is a Test";
                callback(stationInfo)
            } //end getStationInfo

    google.maps.event.addDomListener(window, 'load', initialize);

关于javascript - 信息窗口中的 AJAX 调用 : Scope Issue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20801104/

相关文章:

javascript - Cookie 未出现在 Chrome 控制台的“资源”选项卡中

android - 如何使 Google Mapview 从较小的 mapview 更改为全屏?

c# - 为特定请求禁用 ASP.NET session 刷新

php - 从 PHP foreach 循环获取 Ajax 变量(第二部分)

javascript - 对所有国家的用户使用中文谷歌地图 API 是一个好主意吗?

ios - 像 Uber iOS 应用程序一样在 Google map 上移动标记?

javascript - 在 Angular 7 中处理大型响应式表单

javascript - Kendo Grid 分页不起作用

javascript - 谷歌分析ajax网站的综合浏览量

Javascript:用简单的代码展开/折叠多个 DIV?