我已经实现了基于AJAX的日志功能在我的WP网站,具体如下:WordPress的AJAX登录不重定向成功登录
functions.php
function ajax_login_init(){
wp_register_script('ajax-login-script', get_template_directory_uri() . '/ajax-login-script.js', array('jquery'));
wp_enqueue_script('ajax-login-script');
wp_localize_script('ajax-login-script', 'ajax_login_object', array(
'ajaxurl' => admin_url('admin-ajax.php'),
'redirecturl' => home_url(),
'loadingmessage' => __('Sending user info, please wait...')
));
// Enable the user with no privileges to run ajax_login() in AJAX
add_action('wp_ajax_nopriv_ajaxlogin', 'ajax_login');
}
// Execute the action only if the user isn't logged in
if (!is_user_logged_in()) {
add_action('init', 'ajax_login_init');
}
function ajax_login(){
// First check the nonce, if it fails the function will break
check_ajax_referer('ajax-login-nonce', 'security');
// Nonce is checked, get the POST data and sign user on
$info = array();
$info['user_login'] = $_POST['username'];
$info['user_password'] = $_POST['password'];
$info['remember'] = true;
$user_signon = wp_signon($info, false);
if (is_wp_error($user_signon)){
echo json_encode(array('loggedin'=>false, 'message'=>__('Wrong username or password.')));
} else {
echo json_encode(array('loggedin'=>true, 'message'=>__('Login successful, redirecting...')));
}
die();
}
ajax-login-script.js
jQuery(document).ready(function() {
// Perform AJAX login on form submit
jQuery('form#login_form').on('submit', function(e){
jQuery('form#login_form p.login-status').show().text(ajax_login_object.loadingmessage);
jQuery.ajax({
type: 'POST',
dataType: 'json',
url: ajax_login_object.ajaxurl,
data: {
'action': 'ajaxlogin', //calls wp_ajax_nopriv_ajaxlogin
'username': jQuery('form#login_form #txtEmail').val(),
'password': jQuery('form#login_form #txtPassword').val(),
'security': jQuery('form#login_form #security').val() },
success: function(data){
jQuery('form#login_form p.login-status').text(data.message);
if (data.loggedin == true){
document.location.href = ajax_login_object.redirecturl;
}
}
});
e.preventDefault();
});
});
现在,当我在我的登录弹出框中输入错误的凭据,它成功显示我等待的消息,然后错误Wrong username or password.
。但是,当我使用正确的凭据并按登录,然后它默默登录我,但从来没有刷新页面(实际上它尝试在后台刷新页面,但由于它是一个Ajax请求,我只能看到刷新console
选项卡)。
我想让ajax刷新我发送请求的当前页面。
我认为,罪魁祸首可能是这个片段:
$user_signon = wp_signon($info, false);
if (is_wp_error($user_signon)){
echo json_encode(array('loggedin'=>false, 'message'=>__('Wrong username or password.')));
} else {
echo json_encode(array('loggedin'=>true, 'message'=>__('Login successful, redirecting...')));
}
当$user_signon = wp_signon($info, false);
被调用时,它实际上会记录用户和重定向页面(内AJAX),从来没有进一步执行代码。因此,我没有在我的AJAX成功函数中获取JSON编码数据(这是我实际尝试使用JavaScript重定向页面的地方)。
任何帮助将不胜感激。谢谢
试着颠倒顺序'如果(!is_wp_error(user_signon $))',也可反方向2回声 – Mihai
做到了,没有运气。 – Ali