Freigeben über


Tip 50 – How to query a Data Service using JQuery

Recently I’ve been spending some of my time playing with JQuery.

And because Data Services can expose data in JSON format, I thought I’d use JQuery to grab some data from a Data Service.

Turns out it is pretty simple.

This example isn’t going to win any beauty awards, but it will show you the basics and help you get started.

HTML:

First I put together this page:

<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<script src="Scripts/jquery-1.3.2.js" type="text/javascript">
</script>
<script type="text/javascript">
// JSON CODE IS GOING TO GO HERE
</script>
<body>
<a href='#' id="aShowProducts">Show Products</a><br />
<a href='#' id="aShowCategories">Show Categories</a><br />
<div id="divResults" />
</body>
</html>

As you can see it is trivial.

JQuery Code

Next comes the JQuery code.

The first step as always with JQuery is to hook up some document ready code:

var divResults;
var aShowProducts;
var aShowCategories;
var ajaxRequest;

$(document).ready(function () {
divResults = $('#divResults');
aShowCategories = $('#aShowCategories');
aShowProducts = $('#aShowProducts');
aShowProducts.click(function () {
GetData('Products');
});
aShowCategories.click(function () {
GetData('Categories');
});
});

When the document is ready first I grab hold of some globals:

  • divResults (i.e. <div id=”divResults” />): to hold the results of our query.
  • aShowProducts (i.e. <a href=”#” id=”aShowProducts” …</a>): the ‘Show Products’ link.
  • aShowCategory: the ‘Show Categories’ hyperlink.
  • ajaxRequest: is a variable for holding onto the current ‘request’ so we can abort it if necessary.

Then I hook up the GetData method to the click event of the two hyperlinks, passing in the appropriate Data Service resource set name.

Getting Results

The GetData function looks like this:

function GetData(set) {
var materializer;
switch (set) {
case 'Categories':
materializer = GetRowForCategory;
break;
case 'Products':
materializer = GetRowForProduct;
break;
default:
alert('problems');
}

    if (ajaxRequest!= null)
ajaxRequest.abort();

    ajaxRequest= $.getJSON(
"ProductsService.svc/" + set,
function (data) {
var array = [];
array.push("<table>");
$.each(data.d, function (i, item) {
materializer(array, item)
});
array.push("</table>");
divResults.html(array.join(""));
}
);
}

What this does is based on the ‘set’ argument it chooses a function to use as the materializer, i.e. the function that will produce a <tr> for the corresponding resource type.

So for the ‘Categories’ set I use this function:

function GetRowForCategory(array, item)
{
array.push("<tr><td>");
array.push(item.Id);
array.push("</td><td>");
array.push(item.Name);
array.push("</td></tr>");
}

And for the ‘Products’ set this:

function GetRowForProduct(array,item)
{
array.push("<tr><td>");
array.push(item.Id);
array.push("</td><td>");
array.push(item.Name);
array.push("</td></tr>");
}

Once we’ve chosen the correct materializer next we abort any in progress AJAX requests.

And initiate a new AJAX request using $.getJSON(…) to get JSON from either "ProductsService.svc/Products" or "ProductsService.svc/Categories".

The resulting JSON (i.e. data) is passed to my callback function that builds some html for a table by:

  • using the array.push(…) approach to build the html string.
  • and $.each(data.d) to enumerate over the entities and call the specified materializer for each entity to create a new <tr />

Finally I insert the html – array.join("") – into the div.

Trying it out for yourself

You can Save As the complete html here.

All you need to do is drop the html file in the same website as your DataService change the url to point to your DataService and modify the materializer chooser code and the materializers themselves to match your ResourceSets and ResourceTypes.

Not too hard.

The next step would be to experiment with something to build more interesting queries, see Tip 44 for some ideas.

Oh an BTW I’m new to JQuery so if you spot a newbie mistake please let me know.

Tip50.htm

Comments

  • Anonymous
    April 13, 2010
    This is quite helpful, and more lightweight examples  with JSON would be even more useful.  I'm 9x more likely to write HTML with jQuery than to develop a server-bound client interface, just because it's easier for clients to deploy. Your JavaScript code is fine.  The only thing I would change is to either declare variables aShowProducts & aShowCategories inside the ready() function or not at all (use $('#...') directly), because they're not used elsewhere.

  • Anonymous
    May 06, 2010
    How would I authenticate to Sql Azure's implementation of oData through jquery?

  • Anonymous
    July 28, 2010
    Do you have a CRUD example voor jQuery?

  • Anonymous
    September 22, 2010
    wow im really impressed, a GET example... What about PUT, DELETE, MERGE ???? That are the real interesting things

  • Anonymous
    September 23, 2010
    The comment has been removed

  • Anonymous
    December 18, 2010
    I don't understand the way using batching request. It's a big issue with Odata.Why Odata is not able to update a list at once and send a batch request as well ? Its so complicated with many notion such as Changeset , headers specification , bounders ...Difficult for nothing . Its a pitty