Php Zend登录表单身份验证AJAX错误捕获
Havin in LoginController.php ajax操作如下:Php Zend登录表单身份验证AJAX错误捕获,php,jquery,ajax,zend-framework2,Php,Jquery,Ajax,Zend Framework2,Havin in LoginController.php ajax操作如下: public function ajaxAction() { $form = $this->getServiceLocator()->get('LoginForm'); $form->setData($post); $post = $this->request->getPost(); $response = $this->getResponse()
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";
}
});
});
如果您遇到
内部服务器错误
,则会在操作中出错并引发错误
$post = $this->request->getPost();
$form->setData($post);
您切换了此行,并且从未初始化过$post
。
如果您想实现json响应,我建议您使用zf2本身的ViewJsonStrategy
。在module.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;
以及如何使用jQuery文件将“some_参数”传递给AJAX?请看一下
$result = new JsonModel(array(
'some_parameter' => 'some value',
'success'=>true,
));
return $result;