虽然我不知道您为什么要这样做,但请查看下面的工作代码。请注意行中的注释。我希望这有帮助。
class test{
public function __construct() {
add_action( \'wp_ajax_test2\', array( $this, \'test2\' ) );
/* Front end ajax needs this. */
add_action( \'wp_ajax_nopriv_test2\', array( $this, \'test2\' ) );
add_action( \'wp_enqueue_scripts\', array( $this, \'test1\' ) );
}
public function test1() {
/* in JavaScript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value */
wp_localize_script(\'test-script-ajax\', \'ajaxobj\', array(\'ajaxurl\' => admin_url(\'admin-ajax.php\')));
/* Moved your js to a separate js file and enquing it the WordPress way */
wp_enqueue_script( \'test-script-ajax\', get_stylesheet_directory_uri() . \'/js/test-ajax.js\', array( \'jquery\' ));
}
public function test2(){
echo "success";
exit;
}
}
$ob_call = new test;
$ob_call->test1();
下面是测试ajax的代码。js文件
jQuery(document).ready(function($){
var data = { \'action\':\'test2\' };
jQuery.post( ajaxobj.ajaxurl, data, function( response ) {
alert(response);
});
});