Ajaxorized

JSON in prototype 1.6.0: basic example

October 4, 2007

That right guys, prototype 1.6.0 is on it's way and there is one aspect I want to share with you. In stead of using the old-fashioned 'http-header' way to transport JSON, the prototype framework now eats files with the content-type 'application/json'. A short example:

  1. First, we will use prototype to make an ajax request.
     new Ajax.Request('ajax.php',{ onSuccess: handleSuccess }, method: 'get' });
  2. After this, on the serverside we set the json headers and output the formatted data using the Services_JSON class:
    <?php
    require_once "services_json.class.php";
     
    /* Set the JSON header */
    header("content-type:application/json");
     
    /* Format some data */
    $aData = array("Car", "Plane", "Train");
     
    $oJson = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
     
    /* Output */
    echo $oJson->encode($aData);
    ?>
  3. And finally this alerts 'Car', 'Plain' and 'Train':
    function handleSuccess(transport) {
      $A(transport.responseJSON).each(function(str) {
        alert(str);
      });
    }

Add to: del.icio.us Reddit Slashdot Digg Facebook Technorati Google StumbleUpon Windows Live Yahoo
topFiled under: Ajax, Prototype, Javascript | Willem @ 1:16 am |

2 Comments

RSS feed for comments on this post. TrackBack URL

  1. Alright cool, but what are the advantages? I think i lack some knowledge of the whole JSON thing here.

    Comment by Martijn de Kuijper — October 4, 2007 @ 8:14 am

  2. Well yeah, JSON is alright. By the way, PHP5’s got built-in json functions, so we don’t have to use PEAR no more ;) Thx

    Comment by kovshenin — August 14, 2008 @ 12:02 pm

Leave a comment

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word