Ajax in Zend Framework2

2019-08-07 20:17发布

问题:

Hello People here is my code below,

index.phtml code

<div class="view clearfix" onClick="ajaxinfo()">Info</a></div>

<script>
function ajaxinfo(){

var id = 100;
$.ajax({

    type: "POST",
    url:"http://localhost/zf2/info/format/html",
    data:id,
    success:function(data){alert('ajax data success');},
    error:function(){alert('ajax data failed to fetch');}
    });
return false;

 }
</script>

as you can see iam trying to pass id=100 to info.phtml page and try to get html data back from info.phtml

lets assume info.phtml as

Iam not sure what to write in in controller ... i checked soo many tutorial , but it does not work for ZF2 like

public function init()
{
    $ajaxContent=$this->_helper->helper();
    $ajaxContent->addActionContext('info','html');
    $ajaxContent->initContext();

}

is there any other way to resolve this problem.?

回答1:

you can use something like this in the controller:

     public function addressdeleteAction()
{
    $response = $this->getResponse();    
    $post_data = $request->getPost();    

    $response->setContent(\Zend\Json\Json::encode(array('id' => 100))); 

    return $response;

}


回答2:

To use AJAX with Zend framework I suggest you to create an controller name AsyncController.

Action that are called from your Ajax request must not display layout.

For example:

class AsyncController extends Zend_Controller_Action
{
    public function ajaxAction()
    {
        $this->_helper->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        /* Action you want to do*/
        print json_encode($data);
    }
}

In this example $data must be the result of operations done.

EDIT : I did not see the tag

Sorry I did not see it was for ZF2. This code works for ZF1 but ZF2 changed a lot. I guess the idea is the same but object are really different I guess.