简体   繁体   中英

Use AJAX with Zend Framework 2

I want to use AJAX with Jquery in my ZF2 project. Exactly, I want to change select options when an over select value change.

For this, I try to implement AJAX method. I don't find a good tutorial on internet for my problem, but I try to do this with different sources. This is my code :

Controller :

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

public function getcurrenttimeAction()
{
    $date = new Zend_Date();
    $chaine = $date->toString();
    $this->_helper->json($chaine);
}

This is my my route configuration :

 'administratif_personnel' => array(
            'type' => 'Literal',
            'priority' => 1000,
            'options' => array(
                'route' => '/administratif/personnel',
                'defaults' => array(
                    'controller' => 'Administratif\Controller\Personnel',
                    'action'     => 'liste',
                ),
            ),
            'may_terminate' => true,
            'child_routes' => array(
                [...]
                'getcurrenttime' => array(
                    'type' => 'Literal',
                    'options' => array(
                        'route' => '/getcurrenttime',
                        'defaults' => array(
                            'controller' => 'Administratif\Controller\Personnel',
                            'action'     => 'getcurrenttime',
                        ),
                    ),
                ),
            ),
        ),

And this is my Jquery code in a view (depend of the same controller) I try to do two different method :

<script type="text/javascript">
/*
 * Initialisation de Jquery
 */
$().ready(function() {
    getCurrentTime();
});
function getCurrentTime() {
    $.post("/administratif/personnel/getcurrenttime",{"format":"json"}, function(resp){
        alert("test");
        alert(resp);
    },"json");

    $.ajax({
      url: "/administratif/personnel/getcurrenttime",
    }).done(function(t) {
        console.debug(t);
      console.debug("test");
    });
}

The first method with $.post don't work. I have no any return. But the $.ajax return me a html page. The console.debug(t) send me <html><head>....</head></html> . A page of my website.

Do you have any idea ? I think it's a problem with the route ?

Thank you!

If I correctly understood your question, you need to update a select value depending on the change of another value. So just bind onchange function to the select that changes, get the selected value and send it via AJAX to your Controller action so that you could get the new value and update the second select.

Hers is a solution that you could use in ZF2 :

JS:

$.ajax({ 
    type : 'POST',
    url : '/administratif/personnel/getcurrenttime',
    data : {value: changedValue},
    dataType: 'json',
    success: function(data){  
             //success function
             //current date is in data.currentdate
    },
    error: function(jqXHR,textStatus,errorThrown){
             var error = $.parseJSON(jqXHR.responseText);
             var content = error.content;
             console.log(content.message);
             if(content.display_exceptions)
             console.log(content.exception.xdebug_message);
    },

}) ;

Controller:

public function getcurrenttimeAction()
{
    //get the dependent value sent via ajax
    $value = $this->getRequest()->getPost('value');
    // your logic here....

    $date = date('Y-m-d'); // get the current date
    $data = new JsonModel(array(
            'currentdate' => $date,
    ));
    return $data;
}

You need also to enable ViewJsonStrategy in your module.config.php :

'view_manager' => array(
        //.............

        'strategies' => array(
            'ViewJsonStrategy',
        ),
),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM