我在一个主题的函数中有类似的代码。php文件,但我想将其移动到插件。我组装了以下内容,但由于某种原因,此方法在AJAX调用时遇到问题,并且总是返回零。
这里的目的是,表单将位于前端,可供登录或未登录的用户使用。
以下是我的插件代码:
/*
Plugin Name: AAA Hello World
Plugin URI: http://helloworld.com
Description: AJAX response to form submission
Version: 1.0
Author: John Doe
Author URI: http://helloworld.com
*/
class RespondToMyClicks {
function __construct() {
add_action( \'wp_enqueue_scripts\', array( &$this, \'click_response_styles\' ) );
add_action( \'wp_enqueue_scripts\', array( &$this, \'click_response_scripts\' ) );
if( is_admin() ) {
add_action( \'wp_ajax_the_ajax_hook\', array( &$this, \'process_clicky_form\' ) );
add_action( \'wp_ajax_nopriv_the_ajax_hook\', array( &$this, \'process_clicky_form\' ) );
}
add_shortcode( \'click_response_form\', array( &$this, \'click_response_form\' ) );
}
public function click_response_styles() {
wp_register_style( \'respond-to-my-clicks\', plugins_url( dirname( plugin_basename( __FILE__ ) ) . \'/styles.css\' ) );
wp_enqueue_style( \'respond-to-my-clicks\' );
}
public function click_response_scripts() {
wp_enqueue_script( \'respond-to-my-clicks\', plugin_dir_url( __FILE__ ) . \'ajax.js\', array( \'jquery\' ) );
wp_localize_script( \'respond-to-my-clicks\', \'the_ajax_script\', array( \'ajaxurl\' => admin_url( \'admin-ajax.php\' ) ) );
}
public function process_clicky_form() {
if( !empty( $_POST ) && wp_verify_nonce( $_POST[\'post_filtration\'], \'post_filter_action\' ) ) {
echo "Hello World";
die();
}
}
public function click_response_form() {
$the_form = \'<form id="theForm" method="post" action="">\' .
wp_nonce_field( \'post_filter_action\', \'post_filtration\' ) .
\'<input name="action" type="hidden" value="the_ajax_hook" />
<label class="check"><input type="checkbox" name="change_me" value="" onChange="submit_me();" /> Click me for a response</label>
</form>
<div id="response_area"></div>\';
return $the_form;
}
}
new RespondToMyClicks();
下面是我的Javascript文件代码:
function submit_me() {
jQuery("#response_area").fadeOut("slow");
jQuery.post(the_ajax_script.ajaxurl,
jQuery("#theForm").serialize(),
function(response_from_the_action_function){
jQuery("#response_area").html(response_from_the_action_function).fadeIn("fast");
}
)
}
我已经看了太久了,并且尝试了不同的代码变体,所以希望有人能指出明显的原因,因为我只是错过了它。谢谢