使用PluginBoilerplate 编写插件。我需要打个ajax电话。
我添加到mainplugin.php
类来注册脚本和处理ajax调用。
if ( ! class_exists( \'PoorMansNameSpaceAJAX\' ) ) {
class PoorMansNameSpaceAJAX{
public static $instance = null;
public $nonce = \'\';
public $name = \'ajaxexample\';
public static function getInstance()
{
null === self::$instance AND self::$instance = new self;
return self::$instance;
}
public function __construct(){
# Could as well be: wp_enqueue_scripts or login_enqueue_scripts
add_action( \'admin_enqueue_scripts\', array( $this, \'scriptsEnqueue\' ) );
# Logged in users:
add_action( \'wp_loaded\', array( $this, \'scriptsRegister\' ) );
add_action( \'admin_enqueue_scripts\', array( $this, \'scriptsLocalize\' ) );
add_action( \'admin_init\', array( $this, \'ajaxRegister\' ) );
}
public function scriptsRegister( $page ){
$file = \'page-1.js\';
wp_register_script(
$this->name ,
WPBP_URLPATH . \'/app/files/js/\' . $file ,
array(\'jquery\')
);
}
public function scriptsEnqueue( $page ){
wp_enqueue_script( $this->name );
}
public function ajaxRegister() {
add_action( "wp_ajax_{$this->name}_action", array($this, \'ajaxexample\'), \'1\' );
}
public function scriptsLocalize( $page ){
wp_localize_script( $this->name, "{$this->name}Object", array(
\'ajaxurl\' => admin_url( \'admin-ajax.php\' ),
\'action\' => "{$this->name}_action"
) );
}
public function ajaxexample(){
ob_clean();
echo json_encode( array(
\'success\' => true
) );
wp_die();
}
}
}
在供应商/自动加载后调用的类。包括php。
the main issue 尽管脚本已成功注册、排队和本地化,但ajax回调函数没有执行任何操作。
ajax调用返回空响应:html页面的内容与im中的内容相同。response.success
未设防。
( function( $, plugin ) {
$(document).ready( function() {
$(\'#moreroles\').on(\'click\', function(event) {
event.preventDefault();
/* Act on the event */
var data = plugin;
$.ajax({
url: plugin.ajax_url,
data: data,
beforeSend : function( d ) {
console.log( \'Before send\', d );
}
})
.done( function( response, textStatus, jqXHR ) {
console.log( \'AJAX done\', textStatus, jqXHR, jqXHR.getAllResponseHeaders() );
} )
.fail( function( jqXHR, textStatus, errorThrown ) {
console.log( \'AJAX failed\', jqXHR.getAllResponseHeaders(), textStatus, errorThrown );
} )
.then( function( jqXHR, textStatus, errorThrown ) {
console.log( \'AJAX after finished\', jqXHR, textStatus, errorThrown );
} );
});
} );
} )( jQuery, ajaxexampleObject || {});