Dec 062012
 
Article Javascript

( Read this post in spanish )

In this post we include some examples of javascript code to read a JSON file, and comment about the considerations to take into account when working with JSON documents.

Request a JSON file to the same domain/server.

In the most simple case, the javascript code in the client’s browser retrieves JSON data by performing an ajax request to the same server that served the active page. The easiest way to implement this request using the JQuery library is:

1. Create a test json file “data.json” with the following contents:

{
"mydata": "This is a simple value",
"prime": [ 1, 2, 3, 5, 7, 11, 13 ]
}

2. Place the file in the DocumentRoot of the server, to be reachable with the url “/data.json”. Then, read the file with a function “read_json()” that calls the getJSON method in the JQuery library:

<html>
<head>
    <title>Test - Reading data in JSON format</title>
    <script type="text/javascript" src="/control/jquery-1.7.2.min.js"></script>
    <script type="text/javascript">
        function read_json() {
            $.getJSON("/data.json", function(data) {
                alert("My data: " + data["mydata"]);
                $.each(data["prime"], function(idx,prime) {
                    alert("Prime number: " + prime);
                });
            });
        }
    </script>
</head>
<body onload="read_json();">
</body>
</html>

As we can see, we are also making use of the “each” method in JQuery to traverse the array in the file retrieved.

Request a JSON file to a different domain

The sample code above will fail in Firefox and Chrome browsers, if the url to retrieve the JSON file points to a domain other than the domain that served the page that includes the javascript code that performs the request.

For recurity reasons, the implementations of the javascript interpreter in those browsers does not allow inter-domain request of json files.

However, inter-domain requests of javascript files are permitted. Using this fact, a mechanism known as JSON-P (JSON with Padding) can be used to deliver JSON content wrapped as javascript code.

To do this, the call to to getJSON method is replaced with a call to the “ajax()” method, also iin the JQuery library:

            $.ajax({
                dataType: 'jsonp',
                url: 'http://OTHER-DOMAIN.com/data.php',
                success: function(data) {
                            for (var key in data) {
                              if (data.hasOwnProperty(key)) {
                                  alert(key + " -> " + data[key]);
                              }
                            }
                         },
                 error: function() { alert("Error reading jsonP file"); }
            });

We can see that, instead of requesting a static file “data.json”, the code is requesting a “datos.php” script. The code inside this script is:

<?php echo $_GET["callback"] ?> (
{
    "mydata": "This is a simple value",
    "prime": [ 1, 2, 3, 5, 7, 11, 13 ]
}
);

By specifying “dataType: ‘jsonp’ in the call to ajax() , this method adds a “callback” argument to the url, whose value is dinamically generated. The request reaches the server as:

http://OTHER-DOMAIN.com/data.php?callback=jQuery17200075442985920404215_1352635617448

This value is used in the “data.php” script as the name of a javascript function to wrap the requested JSON data. In this way, the result delivered to the client is a javascript code:

jQuery17200075442985920404215_1352635617448 (
{
    "mydata": "This is a simple value",
    "prime": [ 1, 2, 3, 5, 7, 11, 13 ]
}
);

jQuery takes care of interpreting this result and generate the javascript data structure finally returned.

The behaviour of the ajax call can be tailored with additional parameters “jsonp” and “jsonpCallback”. The meaning of these parameters can be found in the JQuery reference documentation for the ajax method.

 Posted by at 8:52 am

 Leave a Reply

(required)

(required)