Monday, July 21, 2014

.getJSON in jQuery

Ooi Soon Hong, a former colleague at AMD, suggested that he prefers to use .getJSON when he can instead of .ajax. Intrigued, I decided I'd try to refactor the following .ajax implementation in this application to a .getJSON implementation.

<button id="touchme">touch me</button>
<div id="response"></div>
@section scripts
{
   <script language="javascript">
      $('#touchme').bind('click', function () {
         $.ajax({
            type: "POST",
            url: "/api/values?magicstring=@ViewBag.SessionKeyForIdentity",
            dataType: "json",
            success: function (result) {
               $("#response").html(result);
            }
         });
      });
   </script>
}

 
 

I ended up with this:

<button id="touchme">touch me</button>
<div id="response"></div>
@section scripts
{
   <script language="javascript">
      $('#touchme').bind('click', function () {
         $.getJSON("/api/values?magicstring=@ViewBag.SessionKeyForIdentity",
               function(result){
            $("#response").html(result);
         });
      });
   </script>
}

 
 

In order for this to work in the previous code I wrote, I had to change the Post method in ValuesController to be a Get method, but that was really more appropriate anyways truth be told.

No comments:

Post a Comment