2014-07-25 44 views
1

请看看这段代码。我期待它:jquery以奇怪的顺序执行

  1. 执行,节省了两个值(latitudelongitude
  2. 使用这些值在这里= ajax的var center = new google.maps.LatLng(resplat, resplon);

的问题是,代码不按此顺序执行。它“跳过”最初的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 
    }; 
+0

尝试添加'异步:FALSE'使AJAX保持脚本,直到收到响应。 – user3154108

+1

@ user3154108 [该选项已弃用。](http://stackoverflow.com/q/11448011/1420197) –

+0

这很好理解! (我个人被迫与1.10仍然工作>>) – user3154108

回答

1

移动使用resplatresplon里面的AJAX成功回调代码:

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 */ }); 
+0

这样做!我会阅读你发布的链接。非常感谢! – user2915962

+0

@ user2915962不客气。 :-) –