【问题标题】:jQuery return $.getJSON valuejQuery 返回 $.getJSON 值
【发布时间】:2021-12-20 19:59:46
【问题描述】:

如何将“数据”保存到“结果”中?

代码如下:

function GetCoordinates(adres) {
  var result = "";
  jQuery.getJSON('https://maps.google.com/maps/api/geocode/json?address='+adres+'&sensor=false&key=AIzaSyBxhmTCArabnNgXc6IGM7EEpgohO_mECWs',function(data) {
  result = data.results[0].geometry.location["lat"] + ',' + data.results[0].geometry.location["lng"];
  });
  return result;
}

【问题讨论】:

标签: jquery


【解决方案1】:

您正在为匿名函数的结果添加值,因此当您调用 function(data) 时,它正在向 result 添加值,但在父函数中,它在准备好之前返回 result

不幸的是,没有办法从事件监听器返回值。

我仍然清理了你的代码:

function GetCoordinates(adres) {
  var result = "";
  $.getJSON(`https://maps.google.com/maps/api/geocode/json?address=${adres}&sensor=false&key=AIzaSyBxhmTCArabnNgXc6IGM7EEpgohO_mECWs`, (data) => { 
    result = data.results[0].geometry.location["lat"] + "," + data.results[0].geometry.location["lng"];
  });
  return result;
}

【讨论】:

    猜你喜欢
    • 2014-05-19
    • 2011-02-21
    • 2010-11-29
    • 2020-06-30
    • 1970-01-01
    • 2011-02-18
    • 2010-11-16
    • 2011-10-18
    • 1970-01-01
    相关资源
    最近更新 更多