Tuesday, January 10, 2012

take in JSON to craft a hash in jQuery

<html>

   <head>

      <script type="text/javascript" src="jquery-1.5.js">

      </script>

   </head>

   <body>

      <script type="text/javascript">   

         var json = jQuery.parseJSON('{"foo":"bar","baz":"qux"}');

         $.each(json, function(key, value) {

            alert(key);

            alert(value);

         });

      </script>

   </body>

</html>

 
 

The code above will create four alert boxes. They are:

  • foo
  • bar
  • baz
  • quz

 
 

Also, this line of code:

         var json = jQuery.parseJSON('{"foo":"bar","baz":"qux"}');

 
 

...may be replaced with something like this if one wants to bring in content from Razor:

         var json = jQuery.parseJSON('@Html.Raw(Model.Whatever)');

 
 

I've tried to break both versions of this line into two lines today. I have tried to put the JSON into a variable and then put the variable inside of the parseJSON call, but I have had no luck in getting it to work.

No comments:

Post a Comment