Zend中的Ajax实现

I want to implement ajax functionality in zend frame work. So, please try to give one simple example to me.

Well there are two ways using ajax in a zend framework project. Make sure you have ZendX in your library folder. It helps you working with ajax.

The first and most straight forward way is to use it like in any other web project. Copy all your java-script files in the /public/js/ folder.

In my project I use jQuery. So in your _initViewHelpers function you have to enable jQuery:

ZendX_JQuery::enableView($view);

In your layout script you could do this:

if ($this->jQuery()->isEnabled()){
    $this->jQuery()->setLocalPath($this->baseUrl ().
                            '/js/jquery/jquery.min.1.4.4.js')
    echo $this->jQuery()->uiEnable();
}

and in any view script this:

$this->jQuery ()->enable ()->addJavascriptFile ( $this->baseUrl () .
                                                '/js/frontend.js' )

Another way is to let zend create the ajax functions. Watch this HOW TO, it shows you from the beginning how to use ajax in zend framework projects.

Into my Bootstrap.php

protected function _initJQuery()
{
    $this->bootstrap('view');
    $view = $this->getResource('view');
    ZendX_JQuery::enableView($view);
    $viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer();
    $viewRenderer->setView($view);
    Zend_Controller_Action_HelperBroker::addHelper($viewRenderer);
    $view->jQuery()->setRenderMode(ZendX_JQuery::RENDER_JAVASCRIPT | ZendX_JQuery::RENDER_JQUERY_ON_LOAD);
}

as you can see you need ZendX into your library

in Layout.phtml into the

echo $this->headScript()->appendFile('/js/jquery-1.4.4.min.js')
        ->appendFile('/js/jquery-ui-1.8.10.custom.min.js'); ?>

and you'll have JQuery available all-around, then, where you should expect an Ajax response, as I did:

private function noLayout() {
    $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
    $viewRenderer->setNoRender();
    Zend_Layout::getMvcInstance()->disableLayout();
}

this function will disable the layout and will not require a view, so you can do an echo from the Controller Action, as example:

public function listAction() {
    $this->noLayout();
        echo json_encode(array('success' => TRUE));
}

This is "my way", let me know if you find something "better" or just different