Learning Ext JS 3

Show information from JSON format Más videos

Descripción del tema

In this tutorial I want to show how to load the information contained in JSON format in a "Grid", is really easy and basic, but I think it is important to mention for those who are starting to work with this library. This tutorial is very similar to the previous one where we saw how to load data from an XML file, the only thing we will change from the previous tutorial is the record that specifies the information it will contain and the "reader" because now we want to be able to read the JSON information returned by the server.
Image of the grid

Final Image

Resources

Let's download the resources for this tutorial, unzip them and copy the files inside of the folder "grid" on our Web server already installed.

Packaging the tutorial

As we have always done it in this course, we will package the code we will use for this tutorial, remember that this is fundamental and very important, believe me I will never get tired of saying this.
Ext.ns('com.quizzpot.tutorial');

com.quizzpot.tutorial.GridJsonTutorial = {
	init: function(){		
		//code goes here
}

Ext.onReady(com.quizzpot.tutorial.GridJsonTutorial.init,com.quizzpot.tutorial.GridJsonTutorial);

The JSON we're going to use

Now let's define the information that the grid will display, for simplicity I will write the information directly into the code, but remember that this information can be in a database, a text file, Web service or it can come from elsewhere, but for now we will "hardcoded" it.
<?php
	header("Content-Type: text/plain"); 
	
	$data = array(
		'success'=>true,
		'total'=>11,
		'data'=>array(
			array('city'=>'Mexico city','visits'=>684,'pageVisits'=>4.11,'averageTime'=>'00:06:53'),
			array('city'=>'La Victoria','visits'=>443,'pageVisits'=>4.39,'averageTime'=>'00:07:28'),
			array('city'=>'Madrid','visits'=>380,'pageVisits'=>3.11,'averageTime'=>'00:05:22'),
			array('city'=>'Providencia','visits'=>204,'pageVisits'=>3.83,'averageTime'=>'00:08:20'),
			array('city'=>'Bogota','visits'=>204,'pageVisits'=>3.26,'averageTime'=>'00:04:57'),
			array('city'=>'Puerto Madero','visits'=>192,'pageVisits'=>3.56,'averageTime'=>'00:05:07'),
			array('city'=>'Monterrey','visits'=>174,'pageVisits'=>3.90,'averageTime'=>'00:06:06'),
			array('city'=>'Barcelona','visits'=>145,'pageVisits'=>3.28,'averageTime'=>'00:05:39'),
			array('city'=>'Caracas','visits'=>132,'pageVisits'=>4.55,'averageTime'=>'00:06:27'),
			array('city'=>'Rosario','visits'=>116,'pageVisits'=>2.44,'averageTime'=>'00:04:30'),
			array('city'=>'Oaxaca','visits'=>108,'pageVisits'=>1.73,'averageTime'=>'00:02:37')
		)
	);
	
	
	echo json_encode($data);
?>

Creating the “Record”

Once we have defined the format in which the information is delivered to the client (via AJAX), we can create the "Record" we will display in the table.
var Record = Ext.data.Record.create([
	{name: 'city'},
	{name: 'visits', type:'float'},
	{name: 'pageVisits', type:'float'},
	{name: 'averageTime'}
]);
The previous code should look familiar because we have reviewed in previous tutorials, basically we create a "record" with the fields we need to display and that are returned by the server, and define (in some cases) the type of information of the field.

Creating the “Reader”

Now let's write the "Reader" so the store can interpret the information given to us in JSON format.
var reader = new Ext.data.JsonReader({
   totalRecords: "total", 
   root: "data"               
}, Record);
For this case we used the component "JsonReader" and we configured the field of the total of records and the root field which is the principal information.

Creating the Store and loading the information

The next thing we need to do is create the store which shall contain the information locally in order to be manipulated by the grid.
var store = new Ext.data.Store({
	url: 'gridjson.php',
	reader: reader
});

store.load();
You can see that we have configured the "url" that we are going to use to request the information with Ajax, also we have assigned the "Reader" we created earlier, finally we "load" the store.

Saving a few lines of code

So far all we've done is get the information from the server and save it on the store, all the previous lines of code can be reduced substantially as follows:
var store = new Ext.data.JsonStore({
	url: 'gridjson.php',
	root: 'data',
	fields: ['city',{name:'visits',type:'float'},{name:'pageVisits',type:'float'},'averageTime']
});

store.load();
With the previous lines we do exactly the same as we did before, this is convenient when using JSON as a format for information transfer, so the decision to do it in one way or another is up to the developer.

Creating the Grid

Let's create the grid to display the information contained in the store we created previously.
var grid = new Ext.grid.GridPanel({
	store: store, // <--- we assign the store with the information we're going to use
	columns: [
		new Ext.grid.RowNumberer(),
		{header:'City', dataIndex:'city',sortable: true},
		{header:'Visits', dataIndex:'visits',sortable: true},
		{header:'Page/Visits', dataIndex:'pageVisits',sortable: true},
		{header:'Average Time', dataIndex:'averageTime', width:150,sortable: true}
	],
	border: false,
	stripeRows: true
});
We're not doing anything special, we only assigned the store to use, we defined the columns and assign a proper of the "Record" in the store to each column, we also created a column where the rows are numbered, we removed the border so when a table is entered the window will look good and at last we added alternating lines to the rows.

Displaying the grid

There are several ways to display the grid on the screen, this time we will use a window.
var win = new Ext.Window({
	title: 'Grid example',
	layout: 'fit',
	width: 510,
	height:350,
	items: grid
});

win.show();
If you update the browser you will see something like the following image.
Image of the grid

Final Image

Conclusions

So far we have seen how to display information in different formats, which is really simple. In the next chapter we will see how to page this information, every time it gets more interesting so don't forget to subscribe to the Feeds or by email, also remember that use Twitter (quizzpot) to show updates and what we are doing in Quizzpot. If you have any questions or suggestions please leave your comments and don't forget to become a fan in our Facebook page.

Te gustaría recibir más tutoriales como este en tu correo?

Este tutorial pertenece al curso Learning Ext JS 3, te recomiendo revises el resto de los tutoriales ya que están en secuencia de menor a mayor complejidad.

Si deseas recibir más tutoriales como este en tu correo te recomiendo registrarte al curso, si ya eres miembro solo identifícate y registrate al curso, si no eres miembro te puedes registrar gratuitamente!

Si no gustas registrarte en este momento no es necesario! Aún así puedes recibir los nuevos tutoriales en tu correo! Jamás te enviaremos Spam y puedes cancelar tu suscripción en cualquier momento.

¿Olvidaste tu contraseña?

Se el primero en comentar!

Instructor del curso

Crysfel3

Autor: Crysfel Villa

Software engineer with more than 7 years of experience in web development.

Descarga Código Fuente Ver Demostración

Regístrate a este curso

Este tutorial pertenece al curso Learning Ext JS 3, revisa todos los tutoriales que tenemos en este mismo curso ya que están en secuencia y van de lo más sencillo a lo más complicado.

Tendrás acceso a descargar los videos, códigos y material adicional.

Podrás resolver los ejercicios incluidos en el curso así como los Quizzes.

Llevarás un registro de tu avance.