Quick links: Content - sections - sub sections
Jelix 1.1.12

Section: JSON

« AJAX ^ Web services JSON-RPC »
Switch to language: FR

Table of content

JSON is a data format using javascript syntax techniques. this ease greatly the use of JSON encoded data in HTML content.

To send JSON data, there is a specific jResponseJson object. Its alias is "json". All you need to do is to assign your encoded json to the $data property:

  $resp = $this->getResponse('json');
  $resp->data = array( 'lastname'=>'dupont', 'firstname'=>'jean');
  return $resp;

To call the action, in raw javascript :

   http = new XMLHttpRequest();

   //url is a variable which contains the url of the action
   http.open("post", url, true);

   // handleJSONReturn is a function called when the response is received
   http.onreadystatechange = handleJSONReturn;

   // url is a string conatining a php url. 
   // handleJSONReturn is a function treating return state.

ou, avec jQuery :

   $.getJSON( url, function (json) {
      // do something with your json data

The client will receive:

  { "lastname":"dupont", "firstname":"jean"}

And treat it alike

   var json = eval('(' + http.responseText + ')');
   alert(json.lastname + ' ' + json.firstname);

Alternatively, the whole client process with jQuery is :

   $.getJSON( url, function (json) {
       alert(json.lastname + ' ' + json.firstname);

a use case combined with jDao

$countryDao = jDao::get('common~country');
$countries = $countryDao->findAll();
$response = $this->getResponse('json');
$response->data = array();
foreach($countries as $country) {
	$response->datas[] = array('id' => $country->id , 'name' => $country->name);

the client will receive:

  { "id":20, "name":"Europe"}