GetJSON
GetJSON(url,data,callback)
Description
GetJSON loads JSON-encoded data from the server using a GET HTTP request.
url is the location that data is being requested from.
data is the information about the request. If multiple fields are being passed, include them in a single string, separated by ampersand (&) characters. It's best to do an encodeURIComponent() to the data to make sure that spaces and other special characters are properly formatted.
callback is the name of the function in your program to be called when the request is complete. Since the request may take a little while to complete, your app will continue execution immediately after the GetJSON() function is called. The results will not be available until the callback function is called. The returned data is passed to the callback function.
This function is a wrapper for the jQuery $.getJSON() function. It works identically.
Testing an API Function
Here's a trick you can use to test many of these API calls. Combine the URL and the parameters into a single string separated by a question mark ("?"):
http://api.openweathermap.org/data/2.5/weather?q=Toronto
Paste this into a browser and you will get:
{"coord":{"lon":-79.39,"lat":43.65},"sys": {"message":0.0454,"country":"Canada","sunrise":1396263570, "sunset":1396309411},"weather":[{"id":801,"main":"Clouds", "description":"few clouds","icon":"02n"}],"base":"cmc stations", "main":"temp":273.2,"humidity":54,"pressure":1019, "temp_min":271.48,"temp_max":275.15},"wind":{"speed":2.3, "deg":320.501},"rain":{"3h":0},"snow":{"3h":0},"clouds":{"all":12}, "dt":1396259691,"id":6167865,"name":"Toronto","cod":200}
Encoding the Parameters
Certain characters, such as the space key, are not allowed in URL strings. The above example would fail on the city "New York" if it was not encoded. The encodeURIComponent() function converts your parameters into a string which will work perfectly as a URL.
Example
Function btnLoad_onclick() Dim city = "q=" & encodeURIComponent(txtCity.value) Dim URL = "http://api.openweathermap.org/data/2.5/weather" GetJSON(URL, city, weatherData) End Function Sub weatherData(data) MsgBox "Temperature is " & data.main.temp - 273.15 End Sub