You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

jQuery中如何将getJSON返回的data数据存入自定义result变量

问题原因

jQuery.getJSON 属于异步AJAX请求,代码执行不会等待请求返回结果再往下走,所以你的GetCoordinates函数执行到return result时,请求还在发送过程中,给result赋值的回调函数还没触发,最终返回的就是初始定义的空字符串。

可行解决方案

方案1:用回调函数接收结果

把后续要处理坐标的逻辑封装成回调函数,传入GetCoordinates,请求成功后调用回调传参即可:

function GetCoordinates(adres, callback) {
  jQuery.getJSON('https://maps.google.com/maps/api/geocode/json?address='+adres+'&sensor=false&key=AIzaSyBxhmTCArabnNgXc6IGM7EEpgohO_mECWs',function(data) {
    const result = data.results[0].geometry.location["lat"] + ',' + data.results[0].geometry.location["lng"];
    // 把结果传给回调函数处理
    callback(result);
  });
}

// 调用示例
GetCoordinates('要查询的地址', function(coordinate) {
  // 在这里处理拿到的坐标
  console.log(coordinate);
})

方案2:返回Promise配合async/await使用

如果你的运行环境支持ES6+语法,用Promise的写法可读性更高:

function GetCoordinates(adres) {
  // 返回Promise对象,外部可以用await拿结果
  return new Promise((resolve, reject) => {
    jQuery.getJSON('https://maps.google.com/maps/api/geocode/json?address='+adres+'&sensor=false&key=AIzaSyBxhmTCArabnNgXc6IGM7EEpgohO_mECWs')
    .done(function(data) {
      const result = data.results[0].geometry.location["lat"] + ',' + data.results[0].geometry.location["lng"];
      resolve(result);
    })
    .fail(function(err) {
      // 捕获请求失败的情况
      reject(err);
    })
  })
}

// 调用示例,必须在async函数内使用await
async function test() {
  try {
    const coordinate = await GetCoordinates('要查询的地址');
    console.log(coordinate);
  } catch (err) {
    console.log('请求失败', err);
  }
}
test();

注意:不管用哪种方案,都不能直接用同步返回的方式拿异步请求的结果,所有依赖这个坐标的逻辑都必须放在请求成功后的回调、或者await之后的代码块里执行。

内容的提问来源于stack exchange,提问作者Web Atölyesi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 08:15:00