在AJAX成功函数中获取用户名

时间:2017-08-03 08:52:42

标签: php ajax

我正在尝试在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;

    }

非常感谢任何帮助。

1 个答案:

答案 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;    
}

轻微变化,差异很大。 :)