2016-01-03 33 views
-2

我试图将我的位置作为Ajax请求发送。
可能是由于地理定位的异步调用,它不能按预期工作。 地理定位的功能在我的外部功能之后被调用,导致data is empty的答案。地理定位异步调用的问题

$(document).ready(function() { 
    $("button").click(function() { 

     var data = ""; 

     if (...) { // if user wants to share their location 
      function geo_success(position) { 
       console.info("lat:" + position.coords.latitude + " Lot: " + position.coords.longitude); 
       data = { 
        lat : position.coords.latitude, 
        lon : position.coords.longitude 
       }; 
      } 

      function geo_error() { 
       alert("No position available."); 
      } 

      var geo_options = { 
       enableHighAccuracy : true, 
       timeout : 1000, 
       maximumAge : 0 
      }; 

      navigator.geolocation.getCurrentPosition(geo_success, geo_error, geo_options); 
     } 
     if (...) { // if user doesn't want to share their location 
      data = { 
       a : "abc", // some other data 
       b : "def" 
      }; 
     } 
     if (...) { // maybe a third option 
      data = { 
       b : "test", // some other data 
       c : "some data" 
      }; 
     } 

     if (Object.keys(data).length > 0) { 
      console.info("hier"); 
      $.ajax({ 
       method : "GET", 
       url : "test.php", 
       data : data, // finaly send data 
       dataType : 'json', 
       success : function(data) { 
        console.log(data) 
       }, 
       error : function(data) { 
        console.error(data); 
       } 
      }); 
     } else { 
      console.error("data is empty"); 
     } 
    }); 
}); 

<input type="checkbox" id="box1" /> 
<button>ok</button> 

我不能把Ajax请求的geo_success,因为要首先定义data需求。在我的原始代码中(这里只是一个摘录),根据用户的选择,有几种可能的data
所以我只想要1个Ajax请求。

什么可能是一种可能的补救措施?

+0

*“我无法将Ajax请求放入geo_success中,因为我需要首先定义数据。”* - 我无法看到这两件事情是如何相关的。 – JJJ

+0

设置'data'后,将ajax放入geo_success中 –

+0

创建'promise',它将在'geo_success'中解析并在'geo_error'中被拒绝。然后在'.then'或'.catch'中建立你的逻辑。 –

回答

0

可能是由于地理定位的异步调用,它不能按预期工作。地理定位的功能是在我的外部函数之后调用的,导致数据是空的答案。

所以你的意思是这是一个异步调用?:

navigator.geolocation.getCurrentPosition(geo_success, geo_error, geo_options); 

如果是这样的话,那么我怀疑你可以用回拨功能,它提供当操作完成后执行。而且......它看起来像你已经这样做......

​​

所以如果你需要应对的异步操作的结果,只是把代码中的回调函数。

异步就意味着... 不是同步。在完成异步操作后需要发生的任何事情需要调用该操作完成。在你的情况下,当你检查它时,data将永远为空,因为当你创建它时显式地将它设置为空字符串,并且当时没有其他更新。

+0

那么有什么解决方案? – user1170330

+0

@ user1170330:我提出的解决方案不是以某种方式工作吗? – David

+0

如果我理解你是对的,你只是在描述问题。我错过了你的解决方案吗? – user1170330