Zend登录表单身份验证AJAX错误捕获


Zend Login Form Authentication AJAX Error catch

在LoginController.php中添加这样的ajaxAction:

public function ajaxAction()
{
    $form = $this->getServiceLocator()->get('LoginForm');
    $form->setData($post);
    $post = $this->request->getPost();
    $response   = $this->getResponse();
    if (!$form->isValid()){
        // email is invalid; print the reasons
        $json= $form->getMessages();
        $response->setContent('Zend'Json'Json::encode($json));
        return $response;
    }
    $this->getAuthService()->getAdapter()->setIdentity(
        $this->request->getPost('email'))->setCredential(
        $this->request->getPost('password'));
    $result = $this->getAuthService()->authenticate();
    switch ($result->getCode()) {
        case Result::FAILURE_IDENTITY_NOT_FOUND:
            $json = 'No such email found';      
            $response->setContent('Zend'Json'Json::encode($json));
            return $response;
            break;
        case Result::FAILURE_CREDENTIAL_INVALID:
            $json =  'Invalid password';
            $response->setContent('Zend'Json'Json::encode($json));
            return $response;
            break;
    }
    $dbTableAuthAdapter = $this->getServiceLocator()->get('AuthService')[1];
    if($result->isValid()) {
        $result =  $this->getAuthService()->getStorage();
        $result->write($dbTableAuthAdapter->getResultRowObject(array(
                                                        'email',
                                                        'name',
                                                    )));; // Writes email and name to the storage
        $result->write($dbTableAuthAdapter->getResultRowObject(
            null,
            'password'
        ));
        $user_session = new Container('user');
        $user_session->user_name = $this->getAuthService()->getStorage()->read()->name;
        $user_session->user_email = $this->getAuthService()->getStorage()->read()->email; // gets email from storage
        $user_session->login_session = true;
    }
}

和script.js中的loginForm

var urlformLogin = "login/ajax";
$("#Login").submit( function() {
    return false;    
});
$("#btnLogin").click( function() {
    $.ajax({
        url: urlformLogin,
        type: 'POST',
        dataType: 'json',
        async: true,
        data: $("#Login").serialize(),
        success: function (data) {              
                var msgs = $.map(data, function (fieldObj, key) 
                {     return [$.map(fieldObj, function (msg, key) {         return msg;     })] 
                });
              $('#lCheck').html(msgs.join('<hr>'));
            console.log(data);
        },
        error: function () {
            location.href = "auth";
        }
    }); 
});

问题我正在尝试使用AJAX捕获错误消息提交,但我得到一个内部500错误和页面只是重新加载。对于注册表单上下列链接jQuery到PHP数据传输我得到错误消息和回声。但是,我需要从authenticate方法也捕获消息。

在没有ajax的情况下使用processAction

public function processAction()
{
    if (!$this->request->isPost()) {
        return $this->redirect()->toRoute(NULL,
            array( 'controller' => 'login'
            )
        );
    }
    $post = $this->request->getPost();
    $form = $this->getServiceLocator()->get('LoginForm');
    $form->setData($post);
    if (!$form->isValid()) {
        $model = new ViewModel(array(
            'error' => true,
            'form' => $form,
        ));
        $this->layout('layout/login');
        $model->setTemplate('test/login/index');
        return $model;
    }
    $this->getAuthService()->getAdapter()->setIdentity(
        $this->request->getPost('email'))->setCredential(
        $this->request->getPost('password'));
    $result = $this->getAuthService()->authenticate();
    switch ($result->getCode()) {
        case Result::FAILURE_IDENTITY_NOT_FOUND:
                $model = new ViewModel(array(
                    'error_email' => 'No such email found',
                    'form' => $form,
                ));
                $this->layout('layout/login');
                $model->setTemplate('test/login/index');
                return $model;
            break;
        case Result::FAILURE_CREDENTIAL_INVALID:
                $model = new ViewModel(array(
                    'error_password' => 'Invalid password',
                    'form' => $form,
                ));
                $this->layout('layout/login');
                $model->setTemplate('test/login/index');
                return $model;
            break;
    }
    $dbTableAuthAdapter = $this->getServiceLocator()->get('AuthService')[1];
    if($result->isValid()) {
        $result =  $this->getAuthService()->getStorage();
        $result->write($dbTableAuthAdapter->getResultRowObject(array(
                                                        'email',
                                                        'name',
                                                    )));; // Writes email and name to the storage
        $result->write($dbTableAuthAdapter->getResultRowObject(
            null,
            'password'
        ));
        return $this->redirect()->toRoute(NULL, array (
        'controller' => 'login' ,
        'action' => 'confirm'
        ));
    }
}

如果你得到一个Internal Server Error,你在你的行动中搞砸了一些东西,并抛出一个错误。

$post = $this->request->getPost();
$form->setData($post);

您切换了这一行,$post从未初始化。如果你想实现json响应,我建议你使用zf2本身的ViewJsonStrategy。在模块中进行以下更改:config.php

'view_manager' => array(
    /** OTHER SETTINGS **/
    /** ADD THIS **/
    'strategies' => array(
        'ViewJsonStrategy',
    ),
),

在您的操作返回Zend'View'JsonModel,您的输出是干净的json

$result = new JsonModel(array(
    'some_parameter' => 'some value',
    'success'=>true,
));
return $result;