Cross-domain requests with the App Cloud Device API

If you're trying to make AJAX requests from within the Workshop app—for example, with $.get() or $.ajax()—you'll notice nothing happens. Why? AJAX requests cannot be made across different domains.

App Cloud provides a device method for this very reason:

bc.device.fetchContentsOfURL(url, successCallback, errorCallback);

This asynchronous method can be used to load any kind of textual data, from JSON to XML to HTML. For example:

// get latitude/longitude for Beverly Hills, CA

var url = "https://maps.googleapis.com/maps/api/geocode/json?address=90210&sensor=true";

bc.device.fetchContentsOfURL(url,
    function (data) {
        if (data.status === "OK") {
            var coords = [
                data.results[0].geometry.location.lat,
                data.results[0].geometry.location.lng
            ];
            // etc.
        }
        else {
            bc.device.alert("Oops!");
        }
    },
    function (data) {
        bc.device.alert("Oh noes! " + data.errorMessage);
    }
);

Note, bc.device.fetchContentsOfURL() falls back to $.ajax() when running in your desktop browser, so you must start Chrome from the command line with the --disable-web-security flag for it to work. (Do this in testing mode only!) On iOS:

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --disable-web-security

p.s. Get more tips and tricks (and share your own) by joining the Brightcove App Cloud discussion group on Google.