Using JSONP in JS++

JSONP (JSON with padding) is a clever way to work around the web browser's same-origin policy to request data from a different domain or subdomain. The "padding" in JSONP is simply a function call that wraps the JSON data.

For example, if the JSON data is { "foo": "bar" } then the equivalent JSONP call might be callback({ "foo": "bar" }). The "callback" specifies a function to call and send the JSON data to. Most APIs that support JSONP will allow you to specify the name of the callback to call. The callback must be available from the global scope; in most cases, in the web browser, this will mean that the callback is a member of the window object.

In order to define a callback that is available globally in JS++, we can use the following code:

1
2
3
4
5
6
7
8
import System;
 
var global = (function(){ return this; }).call();
 
global.callback = void(json) {
    // Handle the data here
    // ...
};

It is also possible to simply use the Externals.DOM library which provides the window object:

1
2
3
4
5
6
import Externals.DOM;
 
window.callback = void(json) {
    // Handle the data here
    // ...
};

Here is an example of defining a JSONP callback to handle JSON data for a location API:

1
2
3
4
5
6
7
8
9
10
11
12
13
import System;
 
var global = (function(){ return this; }).call();
 
global.callback = void(json) {
    int longitude = json.longitude;
    int latitude = json.latitude;
    string ip = json.ip;
    string country = json.country;
    string isp = json.isp;
     
    Console.log("Hello visitor from " + country + ".");
};

Share

HTML | BBCode | Direct Link