In this post, we will learn
jQuery AJAX using JSON data. The term
JavaScript Object Notation (JSON)
was coined by Douglas Crockford to capitalize on the simple syntax.
JavaScript Object are just sets of key-value pairs, and can be defined
succinctly using curly braces ({}).
JavaScript arrays are defined
on the fly with square brackets([]). Combining these two concepts will
express some very complex and rich data structures.
Following Simple example JSON. This notation can offer a concise alternative to the sometimes-bulky
XML format:
For more complex data, see code below:
14 | "product" : "New Fortuner" , |
20 | "type" : "Fortuner TRD Sportivo Limited Edition" |
Save above code. Named "data.json". We will use it to our jQuery AJAX using JSON in this post.
To call data.json and access data. You can use following code:
1 | $(document).ready( function () { |
2 | $( '#element' ).click( function () { |
3 | $.getJSON( 'data.json' ); |
For more complex data, such as above data, we can use:
01 | $.getJSON( 'data.json' , function (data){ |
02 | $( '#content' ). empty (); |
03 | $.each(data, function (entryIndex, entry){ |
04 | var html = '<div class="data">' ; |
05 | html += '<h3>' + entry[ 'company' ] + '</h3>' ; |
06 | html += '<div class="product">' + entry[ 'product' ] + '</class>' ; |
07 | html += '<div class="type">' + entry[ 'type' ] + '</color>' ; |
08 | $( '#content' ).append(html); |
To be more clear, try this code. Save as "page.html". Place along with "data.json".
03 | <style type= "text/css" > |
06 | <script src= "jquery.js" type= "text/javascript" ></script> |
07 | <script type= "text/javascript" > |
08 | $(document).ready( function () { |
09 | $( '#car' ).click( function () { |
10 | $.getJSON( 'data.json' , function (data){ |
11 | $( '#content' ). empty (); |
12 | $.each(data, function (entryIndex, entry){ |
13 | var html = '<div class="data">' ; |
14 | html += '<h3>' + entry[ 'company' ] + '</h3>' ; |
15 | html += '<div class="product">' + entry[ 'product' ] + '</div>' ; |
16 | html += '<div class="type">' + entry[ 'type' ] + '</div>' ; |
17 | $( '#content' ).append(html); |
27 | <a href= "#" id= "car" >Car</a> |
To handle the entries with colors, which takes another $.each() loop
01 | $(document).ready( function () { |
02 | $( '#car' ).click( function () { |
03 | $.getJSON( 'data.json' , function (data){ |
04 | $( '#content' ). empty (); |
05 | $.each(data, function (entryIndex, entry){ |
06 | var html = '<div class="data">' ; |
07 | html += '<h3>' + entry[ 'company' ] + '</h3>' ; |
08 | html += '<div class="product">' + entry[ 'product' ] + '</div>' ; |
09 | html += '<div class="type">' + entry[ 'type' ] + '</div>' ; |
11 | html += '<div class="color">' ; |
13 | $.each(entry[ 'color' ], function (colorIndex, color){ |
14 | html += '<li>' + color + '</li>' ; |
19 | $( '#content' ).append(html); |