我正在按照本教程使用前端 ajax 从表单提交电子邮件,并在电子邮件中包含当前帖子标题等信息。请注意,我不是 php 或 ajax 专家。任何建议或资源将不胜感激。
我尝试了以下方法 - 但我下面的隐藏输入字段值仅返回一个字符串,我认为这是因为它在页面加载后被包含在内。
jQuery
function submit_me(){
jQuery.post(the_ajax_script.ajaxurl, jQuery("#theForm").serialize()
,
function(response_from_the_action_function){
jQuery("#response_area").html(response_from_the_action_function);
}
);
}
PHP
// enqueue and localise scripts
function plugin_enqueue_scripts() {
wp_enqueue_script( 'my-ajax-handle', plugin_dir_url( __FILE__ ) . 'ajax.js', array( 'jquery' ) );
wp_localize_script( 'my-ajax-handle', 'the_ajax_script', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
add_action('wp_enqueue_scripts', 'plugin_enqueue_scripts');
// THE AJAX ADD ACTIONS
add_action( 'wp_ajax_the_ajax_hook', 'the_action_function' );
add_action( 'wp_ajax_nopriv_the_ajax_hook', 'the_action_function' ); // need this to serve non logged in users
// THE FUNCTION
function the_action_function(){
/* this area is very simple but being serverside it affords the possibility of retreiving data from the server and passing it back to the javascript function */
$name = $_POST['name'];
$title = $_POST['title'];
echo"Title: " . $title;// this is passed back to the javascript function
die();// wordpress may print out a spurious zero without this - can be particularly bad if using json
}
// ADD EG A FORM TO THE PAGE
function hello_world_ajax_frontend(){
$the_form = '
<form id="theForm">
<input id="name" name="name" value = "name" type="text" />
<input name="action" type="hidden" value="the_ajax_hook" /> <!-- this puts the action the_ajax_hook into the serialized form -->
<input id="submit_button" value = "Click This" type="button" onClick="submit_me();" />
<input name="title" type="hidden" value="<?php the_title(); ?>" />
</form>
<div id="response_area">
This is where we\'ll get the response
</div>';
return $the_form;
}
add_shortcode("hw_ajax_frontend", "hello_world_ajax_frontend");
?>