【问题标题】:Fill array with web api ajax call in jQuery在 jQuery 中使用 web api ajax 调用填充数组
【发布时间】:2016-03-19 06:34:44
【问题描述】:

我对 jQuery 或 Javascript 有疑问。我正在尝试在 IP 数组中的 Google 地图中显示更多标志。我设法将 IP 数组传递给函数,但是当我使用 ajax 调用 web api 的次数与数组长度一样多时出现问题,结果 locations 数组为空(未定义);

这是我的代码

function initialize(ipList)
{
    var locations = [];
    var ips = ipList;
    var apiUrl = 'http://freegeoip.net/json/';


//    for(var i = 0; i < ips.length; i++)
//    {
//        jQuery.ajax
//        ({ 
//            url: apiUrl + ips[i], 
//            type: 'POST', 
//            dataType: 'jsonp',
//            success: function(location) 
//            {
//                if(location != null)
//                {
//                    locations.push(location);;
//                }
//            }
//        });
//    }

    $.each(ips, function(i, x) 
    {
        $.ajax
        ({
            url: apiUrl + x,
            type: "POST",
            cache: false,
            success: function(data) 
            {
                if(data != null)
                {
                    locations[i] = location;
                }
            }
        });
    });

    var properties = 
    {
        center: new google.maps.LatLng(locations[0].latitude, locations[0].longitude),
        zoom: 10,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var map = new google.maps.Map(document.getElementById("map"),properties);

    for (var i = 0; i < locations.length; i++)
    {
        var marker = new google.maps.Marker
        ({
            position:{lat: locations[i].latitude, lng: locations[i].longitude},
            animation:google.maps.Animation.BOUNCE,
            title: locations[i].city
        });

        marker.setMap(map);
    }
}

【问题讨论】:

    标签: javascript arrays ajax asp.net-web-api


    【解决方案1】:

    你的意思是

    locations[i] = location; 
    

    而不是

    locations[i] = data;
    

    ?

    您可能有上下文、范围问题。使用回调时,回调函数看不到初始化调用创建的值。最快的解决方案是在初始化之外定义位置。

    【讨论】:

    • 如果你只是附加到位置,你不能总是做位置[locations.length] = location; .
    • 另一个观察结果。 Ajax 是一个异步调用。 javascript 不会停止并等待您的 ajax 调用回答并填充数组,然后再继续执行其余的函数。
    • 我查过locations.push(location);是我想要的。我不是 js 专家。我知道异步不会停止,这就是问题所在,如何解决?!
    【解决方案2】:

    这是完全未经测试的,但更多的是这些方面。我将 map 设为全局变量。

              var map = null;
                function initialize(ipList) {
                    var ips = ipList;
                    var apiUrl = 'http://freegeoip.net/json/';
    
                    $.each(ips, function (i, x) {
                        $.ajax
                        ({
                            url: apiUrl + x,
                            type: "POST",
                            cache: false,
                            success: function (data) {
                                if (data != null) {
                                    porcessPoint(data);
                                }
                            }
                        });
                    });
                }
    
                function processPoint(datapoint) {
                    // assuming the first point is used to create the map
                    if (!map) {
                        var properties =
                        {
                            center: new google.maps.LatLng(datapoint.latitude, datapoint.longitude),
                            zoom: 10,
                            mapTypeId: google.maps.MapTypeId.ROADMAP
                        };
    
                        map = new google.maps.Map(document.getElementById("map"), properties);
                    }
    
                    var marker = new google.maps.Marker
                    ({
                        position: { lat: datapoint.latitude, lng: datapoint.longitude },
                        animation: google.maps.Animation.BOUNCE,
                        title: datapoint.city
                    });
                     marker.setMap(map);
                }
    

    【讨论】:

      【解决方案3】:

      我希望这对某人有用。这就是我更改整个代码的方式:

      $(function() 
      {   
          $('#details').hide();
          $("#btnSubmit").click(function()
          {
              var ipInput = $("#ipInput").val();
      
              $.ajax
              ({
                  type: 'post',
                  url: 'http://localhost/LocationFromIP/public_html/php/traceroute.php',
                  data: {param:  ipInput},
                  success: function(data)
                  {
                      var ipList = data.match(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g);
                      for(var i = 0; i < ipList.length; i++)
                      {
                          $('#details').append(ipList[i] + '<br />');
                      }
                      initialize(ipList);
                      $('#details').show();
                  },
                  error: function (xhr, ajaxOptions, thrownError) 
                  {
                     alert(xhr.status);
                     alert(thrownError);
                  }
              });
          }); 
      });
      
      
      function initialize(ipList)
      {
          var ips = ipList;
          var apiUrl = 'http://freegeoip.net/json/';
      
          var map = null;
          $.each(ips, function(i, x) 
          {
              $.ajax
              ({
                  url: apiUrl + x,
                  type: "GET",
                  cache: false,
                  success: function(location) 
                  {
                      if (i == 0) 
                      {
                          var properties = 
                          {
                              center: new google.maps.LatLng(location.latitude, location.longitude),
                              zoom: 10,
                              mapTypeId: google.maps.MapTypeId.ROADMAP
                          };
      
                          map = new google.maps.Map(document.getElementById("map"),properties);
                      }
      
                      var marker = new google.maps.Marker 
                      ({
                          position:{lat: location.latitude, lng: location.longitude},
                          animation:google.maps.Animation.BOUNCE,
                          title: location.city
                      });
      
                      marker.setMap(map);
                  }
              });
          });
      
      
      }
      

      【讨论】:

        猜你喜欢
        • 2018-09-07
        • 2012-10-08
        • 1970-01-01
        • 1970-01-01
        • 2013-11-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-29
        相关资源
        最近更新 更多