尝试了在主题前台做一个登录框,登陆的功能是实现了,有一个小小的不便,就是如果输错了密码,因为页面又跳回了首页,所以弹出式登录框又被隐藏了,登录成功与否不够明显,二次登录的场合操作也较繁琐,所以想实现前台以ajax的方式登录。实现ajax一共需要修改3个位置,分别是:
- 登录框本身
- 主题footer文件
- 后台functions.php
修改登录框
登陆框里主要是增加了一个消息输出的元素,博主给这个元素命名为 primary-login-message
:
<div id="primary-login" class="section-header">
<i class="fa fa-fw fa-user-circle" aria-hidden="true" style=""></i>
<form id="primary-login-form" action="<?php $this->options->loginAction()?>" method="post" name="login" rold="form">
<input type="hidden" name="referer" value="<?php $this->options->siteUrl(); ?>">
<input id="primary-login-username" type="text" name="name" autocomplete="username" placeholder="<?= _t('请输入用户名') ?>" required/>
<input id="primary-login-password" type="password" name="password" autocomplete="current-password" placeholder="<?= _t('请输入密码') ?>" required/>
<button id="primary-login-submit" type="submit"><?= _t('登录') ?></button>
<?php if ($this->options->allowRegister) : ?>
<span id="primary-register">
<i class="fa fa-fw fa-user-o" aria-hidden="true"></i>
<a href="<?php $this->options->adminUrl('register.php'); ?>" target="_blank" rel="noopener noreferrer nofollow"><?= _t('注册') ?></a>
</span>
<?php endif; ?>
</form>
<div id="primary-login-message"></div>
</div>
footer文件
footer 里主要是家一段js代码,因为采用了php与js混搭的方式,所以必须写在php文件里,如果直接写在js后缀的文件中会报格式错误。
<script>
$('#primary-login-form').submit(function(e) {
e.preventDefault();
var $form = $(this);
var $message = $('#primary-login-message');
$.ajax({
type: 'POST',
url: '<?php $this->options->siteUrl(); ?>',
data: $form.serialize() + '&action=login',
dataType: 'json',
beforeSend: function() {
$message.html('<p class="loading"><?php _e('正在登录...'); ?></p>');
},
success: function(response) {
if (response && response.success) {
$message.html('<p class="success"><?php _e('登录成功,正在跳转...'); ?></p>');
window.location.href = response.referer || '<?php $this->options->siteUrl(); ?>';
} else {
var msg = response ? response.message : '<?php _e('登录请求失败'); ?>';
$message.html('<p class="error">' + msg + '</p>');
}
},
error: function() {
$message.html('<p class="error"><?php _e('请求出错,请重试'); ?></p>');
}
});
});
</script>
后台function.php
后台添加对ajax请求的响应:
// 添加 Ajax 登录处理
function themeHandleLogin($archive)
{
if ($archive->request->isPost() && $archive->request->isAjax() && 'login' == $archive->request->get('action')) {
$user = Typecho_Widget::widget('Widget_User');
$name = $archive->request->get('name');
$password = $archive->request->get('password');
$remember = false;
$result = $user->login($name, $password, $remember);
$response = array(
'success' => $result,
'message' => $result ? _t('登录成功') : _t('用户名或密码无效'),
'referer' => $archive->request->get('referer', $archive->options->siteUrl)
);
$archive->response->throwJson($response);
}
}
// 挂载到 Typecho 的钩子上
Typecho_Plugin::factory('Widget_Archive')->beforeRender = 'themeHandleLogin';
最终效果如上图。