Jquery以奇怪的顺序执行

时间:2014-07-25 09:04:55

标签: jquery ajax google-maps

请查看此代码。我希望它能够:

  1. 执行保存两个值的{ajax(latitudelongitude
  2. 在这里使用这些值= var center = new google.maps.LatLng(resplat, resplon);
  3. 问题是代码没有按此顺序执行。它“跳过”最初的Ajax并在运行其他代码时首先返回它。这使我的两个价值观无用。有人可以解释代码执行顺序背后的逻辑吗?

     function Initialize() {
         $.ajax({
             type: "GET",
             url: 'http://ip-api.com/json',
             dataType: "json",
             success: function (resp) {
                 resplat = resp.lat;
                 resplon = resp.lon;
             }
         });
         // Google has tweaked their interface somewhat - this tells the api to use that new UI
         google.maps.visualRefresh = true;
         var center = new google.maps.LatLng(resplat, resplon);
    
         // These are options that set initial zoom level, where the map is centered globally to start, and the type of map to show
         var mapOptions = {
             zoom: 15,
             center: center,
             mapTypeId: google.maps.MapTypeId.G_NORMAL_MAP
         };
    

1 个答案:

答案 0 :(得分:1)

移动使用ajax成功回调中的resplatresplon 的代码:

function Initialize() {
      $.ajax({
          type: "GET",
          url: 'http://ip-api.com/json',
          dataType: "json",
          success: function (resp) {
              var resplat = resp.lat;
              var resplon = resp.lon;

              // Google has tweaked their interface somewhat - this tells the api to use that new UI
             google.maps.visualRefresh = true;
             var center = new google.maps.LatLng(resplat, resplon);

             // These are options that set initial zoom level, where the map is centered globally to start, and the type of map to show
             var mapOptions = {
                  zoom: 15,
                 center: center,
                 mapTypeId: google.maps.MapTypeId.G_NORMAL_MAP
             };
         }
      });
}

$.ajax是异步调用。您必须等待,直到数据到来(success处理程序)。然后你可以使用它。

另一种方法是添加.done(foo)处理程序:

$.ajax({...}).done(function (...) { /* do something */ });