Here's how I solved the problem:

/app/controllers/test_controller.php
<?php

class TestController extends AppController
{
        var $uses = array();
        var $layout = 'test';
        var $helpers = array('Html', 'Javascript');
        var $components = array('Json');

        function index()
        {
        }

        function getText()
        {
                $this->set('text', $this->Json->encode(array('text' => 'Hello
World!')));
                $this->render('json', 'ajax');
        }
}

?>


/app/views/layouts/test.thtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd";>

<html xmlns="http://www.w3.org/1999/xhtml";>
        <head>
                <?php print $html->charsetTag('UTF-8') ?>
                <?php print $javascript->link('prototype') ?>
        </head>

        <body>
                <?php echo $content_for_layout ?>
        </body>
</html>


/app/views/test/index.thtml
<p>The text below is retrieved asynchronously from the server:</p>
<div id="sometext"></div>

<script type="text/javascript">
        // <![CDATA[

        new Ajax.Request('<?php echo $html->url('/test/getText'); ?>',
{onSuccess:displayText});

        function displayText(response, json)
        {
                document.getElementById('sometext').innerHTML = json.text;
        }

        // ]]>
</script>


/app/views/test/json.thtml
<?php header("X-JSON: $text"); ?>


I'm using the JsonComponent I just added to snippets:
http://cakeforge.org/snippet/detail.php?type=snippet&id=74

To use JsonComponent you also need the JSON-PHP library JSON.php in
your /vendors directory.

So basically in client-side javascript an Ajax.Request calls the
getText action in TestController, which creates a PHP array of some
text and uses the JsonComponent to encode it in JSON format.  That
action then renders a json view that just sends a X-JSON header with
the JSON text.  Then back on the client-side, the onSuccess handler
gets a 2nd argument that Prototype magically sticks the JSON data in.
You can then use that json object to display the data you got from the
server.


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Cake 
PHP" group.
To post to this group, send email to cake-php@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at http://groups.google.com/group/cake-php
-~----------~----~----~----~------~----~------~--~---

Reply via email to