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:

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:

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:

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:

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:

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:

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