Open weather ajax

Skim

New Member
#1
I'm trying to do a ajax call to Openweathermap API and my variables are not being updated once the function leaves ajax. Can someone please explain to me why my var tmp is not being updated.
Mã:
    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
 

Admin

Administrator
Thành viên BQT
#2
Ajax is async, not synchronous

  • your first TMP within the ajax callback will wait for the ajax to complete before execution.
  • your second TMP outside of your ajax callback will execute straight away before waiting the ajax to complete
You can read up on https://rowanmanning.com/posts/javascript-for-beginners-async/

some of the js solutions

  • callbacks ( beginner1 )
  • Async.js ( beginner2 )
  • Promises ( intermediate )
  • ES6 async/await ( advance )
 

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top