开放天气 ajax

Open weather ajax

我正在尝试对 Openweathermap API 进行 ajax 调用,一旦函数离开 ajax,我的变量就不会更新。谁能给我解释一下为什么我的 var tmp 没有更新。

    var url1 = "http://api.openweathermap.org/data/2.5/find?lat=" + marker.position.lat()+"&lon="+marker.position.lng() + "&type=accurate&units=imperial&mode=json&APPID=8cbc2d4c3edf26435cf160f3cee969ed";
    var tmp;
    $.ajax({
    type: 'get',
    dataType: "jsonp",
    url: url1,
    async: false,
    success:function (data) {
tmp =data.list[0].main.temp +"F " + data.list[0].weather[0].description;
console.log(tmp); //it logs correctly here 
  }
});
console.log(tmp); //it says it's undefined here

Ajax是异步的,不是同步的

  • 您在 ajax 回调中的第一个 TMP 将在执行前等待 ajax 完成。
  • 您的 ajax 回调之外的第二个 TMP 将在等待 ajax 完成之前立即执行

您可以继续阅读 https://rowanmanning.com/posts/javascript-for-beginners-async/

部分js解决方案

  • 回调(初学者 1)
  • Async.js (初学者2)
  • 承诺(中级)
  • ES6 async/await(提前)