CodeSnips

Sunday, September 30, 2012

OData with DataJS

If you've been rolling your own OData requests using jQuery, you might want to look at DataJS. It simplifies your code quite a bit and is really easy to use.

Here are examples of jQuery getJson and ajax methods:

// - Roll your own ajax (see OData version below)
$.ajax({
    type: "GET",
    url: "/OData.svc/PortfolioManagerGroups",
    headers: { "Accept" : "application/json",
               "MaxDataServiceVersion" : "2.0" },
    dataType: "json",
    success: listGroups,
    error: ajaxError
});


This is the DataJS vesion of the above jQuery.ajax() example
OData.read("/OData.svc/PortfolioManagerGroups", 
            listGroups, odataError);


This example shows how to do a JsonP formatted query in DataJS.

// I like to wrap this in a function
function readJsonp(qry, callback) {
    OData.defaultHttpClient.enableJsonpCallback = true;
    OData.read(qry, callback, odataError);
    OData.defaultHttpClient.enableJsonpCallback = false;
}

// A query would look like this. Callback should loop through data.results
var qry = "http://someplace.com/Accounts?$select=ACCT_CD,ACCT_NAME&$orderby=ACCT_CD";
readJsonp(qry, listAccounts);

No comments:

Post a Comment