请尝试下面的代码片段。
HTML :
<input name="getUser" id="getUser" value=\'\'/>
<div id="user_data"></div>
JS (js/my-ajax-script.js)
jQuery(document).ready(function($){
$(\'#getUser\').keyup(function(e) {
var user_id = e.target.value;
console.log(user_id);
$.ajax({
url:my_ajax_object.ajaxurl, #add here your ajax url
type:\'POST\',
data:\'action=get_this_user_data&user_id=\'+user_id ,
success:function(results)
{
jQuery(\'#user_data\').html(results);
}
});
});
});
Ajax (add in functions.php)
function my_enqueue() {
wp_enqueue_script( \'ajax-script\', get_template_directory_uri() . \'/js/my-ajax-script.js\', array(\'jquery\') );
wp_localize_script( \'ajax-script\', \'my_ajax_object\',
array( \'ajax_url\' => admin_url( \'admin-ajax.php\' ) ) );
}
add_action( \'wp_enqueue_scripts\', \'my_enqueue\' );
add_action( \'wp_ajax_get_this_user_data\', \'get_this_user_data\' );
add_filter( \'wp_ajax_nopriv_get_this_user_data\', \'get_this_user_data\');
function get_this_user_data()
{
$userid = $_POST["user_id"];
$data = \'\';
$user_info = get_userdata($userid);
if(!empty($user_info))
{
$data .= \'<pre>\';
$data .= \'Username: \' . $user_info->user_login . \'<br/>\';
$data .= \'User roles: \' . implode(\', \', $user_info->roles) . \'<br/>\';
$data .= \'User ID: \' . $user_info->ID . \'<br/>\';
$data .=\'</pre>\';
}
else
{
$data = "user data not found";
}
echo $data;
die();
}
希望这对你有帮助!