Chris Mendez in Javascript, For Developers

Javascript: JSONP requests through DOJO

Normally, I use jQuery framework for Javascript development but I recently worked on a project that required to make a website using ArcGIS for map visualization. ArcGIS requires the DOJO framework which required me to learn a few new tricks.

Here are three ways to accomplish a DOJO-based JSONP request through Ajax.

Example 1

dojo.requre.js

dojo.require("dojo.io.script");  
function initAjaxRequest(){  
    var args = {
        url: "http://main-worldvenues.rhcloud.com/feed",
        content: { 
            q: "?"
            //callback: "jsonData"
        },
        callbackParamName: "callback",
        handleAs: "jsonp",
        load: function(data, params ){
            var json = JSON.parse(data, true)
            console.log( "data", json );
        },
        error: function(error){
            console.log( "An unexpected error occurred: " + error );
        }
    };
    dojo.io.script.get(args);
}
dojo.ready(initAjaxRequest);  

Example 2

dojo.requre.outbound.js

function jsonData(data){  
    var json = JSON.parse(data, true)
    console.log( "data", json );
}

dojo.require("dojo.io.script");  
function initAjaxRequest(){  
    var args = {
        url: "http://main-worldvenues.rhcloud.com/feed",
        content: { 
            q: "?",
            callback: "jsonData"
        },
        handleAs: "jsonp",
        load: function(res, params ){
        },
        error: function(error){
            console.log( "An unexpected error occurred: " + error );
        }
    };
    dojo.io.script.get(args);
}
dojo.ready(initAjaxRequest);  

Example 3

Require.js

// Require the xhr module
require(["dojo/io/script", "dojo/_base/array", "dojo/json", "dojo/domReady!"], function(script, arrayUtil, JSON) {  
    script.get({
        // The URL to get JSON from Twitter
        url: "http://main-worldvenues.rhcloud.com/feed",
        callbackParamName: "callback",
        handleAs: "json",
        content: {
        },
        load: function(items) {
            var items = JSON.parse(items, true);
            arrayUtil.forEach(items.rows,function(item) {
                console.log(item);
            });
        },
        error: function(err) {
            console.log("Error!", err);
        }
    })
});