GetJSON: Difference between revisions

From NSB App Studio
Jump to navigation Jump to search
Created page with "getJSONP(''url'',''data'',''callback'') == Description == Note: This function can be replaced by the Ajax() function. ReadFile will read ''filename'' which can either b..."
 
No edit summary
 
(20 intermediate revisions by 4 users not shown)
Line 1: Line 1:
getJSONP(''url'',''data'',''callback'')
GetJSON(''url''[,''data''][,''callback''])


== Description ==
== Description ==


Note: This function can be replaced by the [[Ajax]]() function.
GetJSON loads JSON-encoded data from the server using a GET HTTP request.  


ReadFile will read ''filename'' which can either be deployed with the app or be on the same server as the app. If the file is to be deployed with the app, include it in the manifest. This function will only work when deployed to a website: it will not work when running in the local browser.  
''url'' is the location that data is being requested from.


Use ''method'' to define the access method. Usually this parameter can be left out: the default is Get. The next most common value for this is Post. Post responses are never cached, whereas Get responses can be. Post also allows larger data transfers. Other methods are Connect, Delete, Head, Options, Put, Trace, or Track. For more information on these options, look up XMLHttpRequest on the web. The function is based on XMLHttpRequest. See the ReadFile.nsx sample.
''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/decodeURIComponent|encodeURIComponent]]() to the data to make sure that spaces and other special characters are properly formatted.


It returns two values: .status = 0 or 200 if the file was read successfully and .responseText which has the entire contents of the file. If the file is not read successfully, a different status code is returned in .status.
''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. If the JSON being loaded is invalid, callback will not be executed.


There is no equivilent WriteFile. Use [[sql|Sql]], [[localstorage|LocalStorage]] or the PhoneGap API to save data.
If you are using this with VoltBuilder, remember to [http://docs.phonegap.com/en/3.4.0/guide_appdev_whitelist_index.md.html#Whitelist%20Guide add the remote site to your whitelist]. Do this by adding lines to your configxml project property.


== Example ==
For uploading data, GetJSON has a limit imposed by a server setting: it is usually 8192 bytes. There is no response size limit. If you need to send more information, use the [[Ajax]]() function.
 
This function is a wrapper for the jQuery [http://api.jquery.com/jQuery.getJSON/ $.getJSON()] function. It works identically.
 
=== Server side ===
 
GetJSON a much easier and more compatible way of calling a cross domain web server.  GetJSON supports this out of the
box.  You will have to:
 
# Append ?callback=? to your URL.
# Change your MIME type to application/javascript
# Read in the callback parameter server side and respond with the JSON wrapped in the following:
 
<pre>
    cbvalue(json);
</pre>
 
cbvalue is the value of callback, json is your JSON data.
 
This will allow you to make cross domain requests without messing with headers or browser settings.
 
=== 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 ("?"):
<pre>
<pre>
Rem ReadfileFile example
http://api.openweathermap.org/data/2.5/weather?q=Toronto
filename="g.txt"
req=ReadFile(filename)
If req.status=200 Then
  MsgBox req.responseText
Else
  MsgBox "File could not be read"
End If
</pre>
</pre>
Paste this into a browser and you will get:
<pre>
{"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}
</pre>
=== 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/decodeURIComponent|encodeURIComponent]]() function converts your parameters into a string which will work perfectly as a URL.
== Example ==
<tabber>
JavaScript=
<syntaxhighlight lang="JavaScript">
function btnLoad_onclick() {
  var city, url;
  city = "q=" + encodeURIComponent(txtCity.value);
  url = "http://api.openweathermap.org/data/2.5/weather";
  GetJSON(url, city, weatherData);
}
function weatherData(data) {
  alert("Temperature is " + (data.main.temp - 273.15));
}
</syntaxhighlight>
|-|
BASIC=
<syntaxhighlight lang="vb.net">
Function btnLoad_onclick()
  Dim city, url
  city = "q=" & encodeURIComponent(txtCity.value)
  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
</syntaxhighlight>
</tabber>


== Related Items ==
== Related Items ==


[[ajax|Ajax]]
* [[Ajax]]
* [[EncodeURIComponent/decodeURIComponent]]


[[Category:Language Reference]]
[[Category:Language Reference]]


[[Category:Miscellaneous]]
[[Category:Miscellaneous]]

Latest revision as of 22:56, 12 November 2020

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. If the JSON being loaded is invalid, callback will not be executed.

If you are using this with VoltBuilder, remember to add the remote site to your whitelist. Do this by adding lines to your configxml project property.

For uploading data, GetJSON has a limit imposed by a server setting: it is usually 8192 bytes. There is no response size limit. If you need to send more information, use the Ajax() function.

This function is a wrapper for the jQuery $.getJSON() function. It works identically.

Server side

GetJSON a much easier and more compatible way of calling a cross domain web server. GetJSON supports this out of the box. You will have to:

  1. Append ?callback=? to your URL.
  2. Change your MIME type to application/javascript
  3. Read in the callback parameter server side and respond with the JSON wrapped in the following:
    cbvalue(json);

cbvalue is the value of callback, json is your JSON data.

This will allow you to make cross domain requests without messing with headers or browser settings.

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() {
  var city, url;
  city = "q=" + encodeURIComponent(txtCity.value);
  url = "http://api.openweathermap.org/data/2.5/weather";
  GetJSON(url, city, weatherData);
}

function weatherData(data) {
  alert("Temperature is " + (data.main.temp - 273.15));
}

Function btnLoad_onclick()
  Dim city, url
  city = "q=" & encodeURIComponent(txtCity.value)
  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

Related Items