Wordpress插件类设置Ajax



我使用class制作插件,我需要在前端运行一些Ajax。所有脚本都已正确排队。当我触发呼叫时,我得到400错误。

class CCYTFeatured {
public function __construct(){
add_action( 'wp_enqueue_scripts', array($this, 'cc_yt_scripts' ));
add_action( 'wp_ajax_cc_get_featured_yt', array( $this, 'cc_get_featured_yt' ) );
add_action( 'wp_ajax_nopriv_cc_get_featured_yt', array( $this, 'cc_get_featured_yt' ) );
} 
public function cc_yt_scripts() {
// JAVASCRIPT
wp_register_script( 'cc_yt_script',
plugins_url( '/js/cc_yt.js', __FILE__ ),
array('jquery'),
cc_yt_version(),
true
);
wp_localize_script(
'cc_yt_script',
'cc_yt_ajax',
array(
'ajax_url' => admin_url( 'admin-ajax.php' )
)
);
wp_enqueue_script('cc_yt_script');
}
public function cc_get_featured_yt(){
echo 'SUCCESS!';
die();
}

我的ajax调用是:

function start_yt(){
jQuery('#cc_yt_light_wrap').show();
// REGISTER NEW ENTRY USING AJAX
jQuery.ajax({
url: cc_yt_ajax.ajax_url,
type: 'POST',
data: {
action : 'cc_get_featured_yt',
},
async: true,
success: function(response) {
console.log(response);
}
});
}

谢谢你的帮助!X(

试试这个:将方法名称从cc_get_featured_yt更改为get_featured,并在类中的所有位置更改方法名称。然后在ajaxcall中输入以下代码:

data: {
action : 'featured_yt',
}

我认为methodname中的get是一个关键字。这对我有效。

代码正常,

我上课的方式不对。

我把这叫做一个主题。相反,我创建了一个新方法,并从__construct((中移除了所有内容。

启动我的类并调用插件文件中的方法。在我重新开始上课后,只调用了主题中所需的方法。工作得很好。

最新更新