【问题标题】:Open weather ajax打开天气ajax
【发布时间】:2019-03-06 01:37:50
【问题描述】:

我正在尝试对 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 api openweathermap


    【解决方案1】:

    Ajax 是异步的,不是同步的

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

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

    一些js解决方案

    • 回调(初学者1)
    • Async.js (初学者2)
    • 承诺(中级)
    • ES6 异步/等待(高级)

    【讨论】:

    • async 在我的 ajax 调用中设置为 false 怎么会出现其他情况?
    • 它在 jquery api doc 上已弃用,你为什么要同步?它将冻结浏览器直到检索到结果
    猜你喜欢
    • 2015-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-22
    • 2017-04-12
    • 2018-09-11
    • 1970-01-01
    相关资源
    最近更新 更多