我正在尝试在AJAX请求成功时显示用户名。 我遇到的问题是该名称仍为空白。
简化代码(如果语句,检查和其他无关代码,则删除)
wp_localize_script('follow-me-ajax', 'ajax_setting', array(
'ajax_url' => admin_url('admin-ajax.php'),
'ajax_nonce' => wp_create_nonce('km-ajax-create-nonce'),
'ajax_follow_success' => $this->follow_me_success(),
));
AJAX致电
var user_to_follow = $('.km-author-follow a.km-meta-badge').attr('id');
$.ajax( {
url : ajax_setting.ajax_url,
type : 'post',
data: {
action : 'theme_ajax_follow_me',
security : ajax_setting.ajax_nonce,
'data-follow-user' : user_to_follow,
},
success: function( data ) {
$('.km-follow-me').html( ajax_setting.ajax_follow_success ).hide().fadeIn( 'slow' );
console.log( user_to_follow );
},
} )
在wp ajax函数中我使用了这个
public function theme_addon_ajax_follow_me() {
...
$target_user = isset( $_POST['data-follow-user'] ) ? $_POST['data-follow-user'] : false;
if( ! empty( $_POST['data-follow-user'] ) ) {
$this->kiwi_follow_user( $current_user, $target_user );
}
wp_die();
}
接下来;此函数将$target_user ID
发送到km_follow_me_author_name
public function kiwi_follow_user( $current_user = 0, $user_to_follow = 0 ) {
...
$args = array(
'user_id' => $current_user,
'follow_to' => $user_to_follow
);
$response_success = $this->km_follow_me_author_name( $args );
}
根据AJAX的$_POST['data-follow-user']
public function km_follow_me_author_name( $args = array() ) {
$author_info = get_userdata( $args['follow_to'] );
$author = $author_info->display_name;
return $author;
}
成功消息以及出错的地方。 $name
仍为空白。
public function follow_me_success() {
$name = $this->km_follow_me_author_name();
$content = sprintf( esc_html__( 'You\'re now following %s.', 'theme' ), $name );
return $content;
}
非常感谢任何帮助。
答案 0 :(得分:0)
首先,我从wp_localize_script
'ajax_follow_success' => $this->follow_me_success(),
然后将成功函数从AJAX更改为:
$('.km-follow-me').html(data).hide().fadeIn( 'slow' );
然后我在public function kiwi_follow_user
内使用了:
if ( ! empty( $response ) && $response !== FALSE ) {
$this->km_follow_me_success( $user_to_follow );
}
在follow_me_success
函数中,我将return
替换为echo
。
public function follow_me_success( $target_user = 0 ) {
$name = $this->km_follow_me_author_name( $target_user );
$content = sprintf( esc_html__( 'You\'re now following %s.', 'theme' ), $name );
echo $content;
}
轻微变化,差异很大。 :)