2010-02-24 29 views

回答

3

把这个

public function init() 
{ 
    $contextSwitch = $this->_helper->getHelper('contextSwitch'); 
    $contextSwitch->addActionContext('test', 'json') 
        ->initContext(); 
} 

创建一个测试动作

public function testAction() 
{ 
    $this->view->var1 = "I'm testing"; 
} 

然后使用jQuery在您的视图执行请求

<script type="text/javascript"> 

$(document).ready(function(){ 
    $('#display').ajaxStart(function(){ 
     $(this).html('Loading...'); 
    }); 

    str = $('#test').val(); 
    $('#link').bind('click',function(event){ 
     event.preventDefault(); 
     $.post(
     this.href, 
     { var1: str, format: 'json' }, 
     function(data){ 
      $('#display').html(data.var1); 
     }, 
     "json" 
     );   

    }); 

}); 

</script> 
<input type="text" name="test" id="test" value="just testing" /> 
<p> 
    <a href="<?php echo $this->url(array('controller' => 'index', 'action' => 'test')); ?>" id="link">Testar</a> 
</p> 

<div id="display">...</div> 
1

您可以使用这样的事情在您的控制器中:

public function testAction() { 
     // Remove all of your HTML stuff 
     $this->_helper->layout->disableLayout(); 
     // PHP to create an array form database or something 
     // This will return the info as json. It takes care of the header and everything else! 
     return $this->_helper->json->sendJson(array('test')); 
    }