Zend的登录窗体身份验证AJAX错误捕捉窗体、身份验证、错误、Zend

2023-09-10 20:28:18 作者:ParTing丶忆

就吃在LoginController.php ajaxAction是这样的:

 公共职能ajaxAction()
{
    $形式= $这个 - > getServiceLocator() - >获得('LoginForm的');
    $形式 - >使用setData($后);
    $后= $这个 - >请求 - >的getPost();
    $响应= $这个 - > GETRESPONSE();
    如果($形式 - >!的isValid()){
        //电子邮件无效;打印的原因
        $ JSON = $形式 - >的getMessages();
        $响应 - > setContent(\ Zend的\的Json \ Json的::连接code($ JSON));
        返回$反应;
    }

    $这 - > getAuthService() - > getAdapter() - > setIdentity(
        $这个 - >请求 - >的getPost(电子邮件)) - > setCredential(
        $这个 - >请求 - >的getPost('密码'));
    $结果= $这个 - > getAuthService() -  GT;身份验证();

    开关($ result->获得code()){
        案件结果:: FAILURE_IDENTITY_NOT_FOUND:
            $ JSON ='没有这样的电子邮件中;
            $响应 - > setContent(\ Zend的\的Json \ Json的::连接code($ JSON));
            返回$反应;
            打破;

        案件结果:: FAILURE_CREDENTIAL_INVALID:
            $ JSON ='密码无效;
            $响应 - > setContent(\ Zend的\的Json \ Json的::连接code($ JSON));
            返回$反应;
            打破;
    }

    $ dbTableAuthAdapter = $这 - > getServiceLocator() - >得到('AuthService')[1];
    如果($ result->的isValid()){
        $结果= $这个 - > getAuthService() - > getStorage();
        $ result-→写($ dbTableAuthAdapter-> getResultRowObject(阵列(
                                                        '电子邮件',
                                                        '名称',
                                                    )));; //写电子邮件,姓名与存储
        $ result-→写($ dbTableAuthAdapter-> getResultRowObject(
            空值,
            '密码'
        ));

        $ USER_SESSION =新容器(用户);
        $ user_session->用户名= $这个 - > getAuthService() - > getStorage() - >阅读() - >名称;
        $ user_session-> USER_EMAIL = $这个 - > getAuthService() - > getStorage() - >阅读() - >电子邮件; //从存储中获取电子邮件
        $ user_session-> login_session = TRUE;
    }
}
 

和中的script.js下面的登录表单的脚本

  VAR urlformLogin =登录/ AJAX;
$(#登录)。递交(函数(){
    返回false;
});
$(#btnLogin)。点击(函数(){
    $阿贾克斯({
        网址:urlformLogin,
        键入:POST,
        数据类型:JSON,
        异步:真正的,
        数据:$(#登录)序列化()。
        成功:功能(数据){
                VAR封邮件= $ .MAP(数据,功能(fieldObj,键)
                {返回[$ .MAP(fieldObj,函数(MSG,键){返回味精;})]
                });
              $('#lCheck)HTML(msgs.join('< HR>'));
            的console.log(数据);
        },
        错误:函数(){
            location.href =身份验证;
        }
    });
});
 

问题我试图赶上使用AJAX上提交的错误信息,但我得到一个内部500错误和页面只是重新加载。对于登记表上的以下链接 jQuery来PHP数据传输我得到错误信息和呼应他们。但是,我还需要搭上邮件从验证方式。

娄如果使用的processAction没有Ajax。

 公共职能的processAction()
{
    如果($这 - >!请求 - > isPost()){
        返回$这个 - >重定向() - > toRoute(NULL,
            阵列(控制器=>'登录'
            )
        );
    }
    $后= $这个 - >请求 - >的getPost();
    $形式= $这个 - > getServiceLocator() - >获得('LoginForm的');

    $形式 - >使用setData($后);
    如果($形式 - >!的isValid()){
        $模式=新的视图模型(阵列(
            '错误'=>真正,
            '形式'=> $形式,
        ));
        $这个 - >布局(布局/登录');
        $建模> setTemplate(测试/登录/指数');
        返回$模型;
    }
    $这 - > getAuthService() - > getAdapter() - > setIdentity(
        $这个 - >请求 - >的getPost(电子邮件)) - > setCredential(
        $这个 - >请求 - >的getPost('密码'));
    $结果= $这个 - > getAuthService() -  GT;身份验证();
    开关($ result->获得code()){
        案件结果:: FAILURE_IDENTITY_NOT_FOUND:
                $模式=新的视图模型(阵列(
                    error_email'=> 没有这样的电子邮件中',
                    '形式'=> $形式,
                ));
                $这个 - >布局(布局/登录');
                $建模> setTemplate(测试/登录/指数');
                返回$模型;
            打破;

        案件结果:: FAILURE_CREDENTIAL_INVALID:
                $模式=新的视图模型(阵列(
                    error_password'=> '无效的密码',
                    '形式'=> $形式,
                ));
                $这个 - >布局(布局/登录');
                $建模> setTemplate(测试/登录/指数');
                返回$模型;
            打破;
    }
    $ dbTableAuthAdapter = $这 - > getServiceLocator() - >得到('AuthService')[1];
    如果($ result->的isValid()){
        $结果= $这个 - > getAuthService() - > getStorage();
        $ result-→写($ dbTableAuthAdapter-> getResultRowObject(阵列(
                                                        '电子邮件',
                                                        '名称',
                                                    )));; //写电子邮件,姓名与存储
        $ result-→写($ dbTableAuthAdapter-> getResultRowObject(
            空值,
            '密码'
        ));

        返回$这个 - >重定向() - > toRoute(NULL,阵列(
        控制器=> '登录' ,
        '行动'=> '确认'
        ));
    }
}
 
C 中winform能否多个form合并

解决方案

如果你得到一个内部服务器错误您已经搞砸了的东西在你的行动,并抛出一个错误

  $后= $这个 - >请求 - >的getPost();
$形式 - >使用setData($后);
 

您切换此行, $交从未被初始化。 如果你想实现一个JSON响应,我建议你使用 ViewJsonStrategy 通过ZF2本身。作出以下修改您的 module.config.php

 'view_manager'=>阵列(
    / **其他设置** /

    / **添加此** /
    '战略'=>阵列(
        ViewJsonStrategy,
    ),
),
 

在你的行动回报的Zend \查看\ JsonModel 和你的输出是干净的JSON

  $结果=新JsonModel(阵列(
    SOME_PARAMETER'=> 一些价值,
    '成功'=>如此,
));
返回$结果;
 

Havin in LoginController.php ajaxAction like this:

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;
    }
}

And in script.js following script for 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";
        }
    }); 
});

Problem I am trying to catch error messages using AJAX on submit but i get an internal 500 error and page just reloads. For Register Form on following link jQuery to PHP data transfer i get error messages and echo them. But there i need to catch messages also from authenticate method.

Bellow if processAction used without ajax.

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'
        ));
    }
}

解决方案

if you get a Internal Server Error you have messed up something in your action and an error is thrown.

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

you switched this line and $post was never initialised. if you like to implement a json response i suggest you to use the ViewJsonStrategy by zf2 itself. make the following changes in your module.config.php

'view_manager' => array(
    /** OTHER SETTINGS **/

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

in your action return a Zend\View\JsonModel and your output is clean json

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