fredag 2 maj 2008

Using jQuery with JSon-enabled WCF Services

This continues our discoveries in the articles "Returning true JSON from WCF services" and "Return JSON from Ajax-enabled WCF Service", and will explain how we call our service from jQuery using the $.getJSON-call.


Download the .js file from http://jquery.com/, make a html or aspx-page and point a script-src-tag to the downloaded script.

Below I have added a simple jQuery-script that gets our example-data from the WCF service and alerts the results.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Test jQuery, WCF and JSon</title>
    <script src="script/jquery-1.2.2.js" type="text/javascript"></script>
    <script type="text/javascript">
    $().ready(function()    
    {
        $("#myButt").click(function()
        {
            $.getJSON("TrueJSON.svc/DoWork",function(data)
            {
                alert("Name=" + data.Name + "\nId=" + data.Id + "\nNoPublicGet="+data.NoPublicGet + "\nInternalProperty=" + data.InternalProperty );
            });
        });
    });
    </script>
</head>
<body>
<input type="button" value="Get values from server" id="myButt" />
</body>
</html>

Simple, isn't it?

If you are unfamiliar with the jQuery syntax, read more about it on http://jquery.com/.


Ok, lets move on, now we are going to wrap things up and show how we can send in some parameters to our WCF Service in the article "Calling WCF from jQuery using parameters".


Inga kommentarer: