【问题标题】:return JSON value out of function?从函数中返回 JSON 值?
【发布时间】:2015-12-16 08:31:00
【问题描述】:

我正在尝试使用 Google 的地理编码器从函数中返回 lat 值,但它不起作用。我收到“意外令牌”的错误消息?

function getLat(address) {
  var googleToken = "my-google-token"
  var geoUrl = "https://maps.googleapis.com/maps/api/geocode/json?address=" + address + "&key=" + googleToken;
    $.getJSON(geoUrl, function(data) {
      return data.results[0].geometry.location.lat);
    });
}

$('body').html(getLat('New+York,+NY'));

【问题讨论】:

    标签: jquery function google-geocoder


    【解决方案1】:

    问题是使用XMLHTTPRequest 加载外部资源是一个异步任务。

    更好更简单的方法是

    function getLat(address, $el, type) {
      var googleToken = "my-google-token"
      var geoUrl = "https://maps.googleapis.com/maps/api/geocode/json?address=" + address + "&key=" + googleToken;
        $.getJSON(geoUrl, function(data) {
          if(type=="html")
             $el.html(data.results[0].geometry.location.lat);
          else if(type=="text")
             $el.text(data.results[0].geometry.location.lat);
        });
    }
    
    getLat('New+York,+NY', $("body"), "html");
    getLat('New+York,+NY', $("div"), "text");
    

    【讨论】:

    • 谢谢。但这似乎对我不起作用。
    • 您现在不能删除return吗?
    • 你能告诉我geoUrl的输出吗?
    • 另外,我正在寻找一种在其他函数中调用它的方法,例如$('div').text(getLat('New+York,+NY'));。所以这种格式不适合我?
    • 检查更新的代码。它仍然对你有用:)!
    【解决方案2】:

    异步函数需要回调,或者你可以使用promises

    function getLat(address) {
        return $.getJSON('https://maps.googleapis.com/maps/api/geocode/json', {
           adress : adress,
           key    : "my-google-token"
        });
    }
    
    getLat('New+York,+NY').done(function(data) {
        $('body').html(data.results[0].geometry.location.lat);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-12
      • 2019-06-02
      • 2014-06-23
      • 2022-11-25
      相关资源
      最近更新 更多