您的表单显示了两次,因为您错误地处理了AJAX,并且使用了将表单显示为响应的模板。您需要将表单代码包装在一个if-else语句中,该语句检查当前是否有AJAX请求正在运行。
但更明显的是,您对AJAX的理解完全错误。WordPress有一个很好的有文档记录的API,它可以让您将所有代码从模板中取出,放到其他地方(并减少代码量)。
请参见此处了解如何:http://www.garyc40.com/2010/03/5-tips-for-using-ajax-in-wordpress/
e、 g。
// embed the javascript file that makes the AJAX request
wp_enqueue_script( \'my-ajax-request\', plugin_dir_url( __FILE__ ) . \'js/ajax.js\', array( \'jquery\' ) );
// declare the URL to the file that handles the AJAX request (wp-admin/admin-ajax.php)
wp_localize_script( \'my-ajax-request\', \'MyAjax\', array( \'ajaxurl\' => admin_url( \'admin-ajax.php\' ) ) );
// if both logged in and not logged in users can send this AJAX request,
// add both of these actions, otherwise add only the appropriate one
add_action( \'wp_ajax_nopriv_myajax-submit\', \'myajax_submit\' );
add_action( \'wp_ajax_myajax-submit\', \'myajax_submit\' );
function myajax_submit() {
// get the submitted parameters
$postID = $_POST[\'postID\'];
// generate the response
$response = json_encode( array( \'message\' => \'why hello there javascript, Im doing fine thankyou\' ) );
// response output
header( "Content-Type: application/json" );
echo $response;
// IMPORTANT: don\'t forget to "exit"
exit;
}
javascript:
jQuery.post(
// see tip #1 for how we declare global javascript variables
MyAjax.ajaxurl,
{
// here we declare the parameters to send along with the request
// this means the following action hooks will be fired:
// wp_ajax_nopriv_myajax-submit and wp_ajax_myajax-submit
action : \'myajax-submit\',
// other parameters can be added along with "action"
message : \'hello wordpress this is javascript, how are you?\'
},
function( response ) {
alert( response );
}
);
这样做将表单代码从AJAX注册逻辑中分离出来,使您描述的问题几乎不可能实现。
还要看看我链接的那篇文章中提到的jquery表单,它进一步简化了事情。
对于布朗尼点,当使用WordPress AJAX API时,WordPress定义常量DOING_AJAX
让您知道您正在进行AJAX调用。使用此选项可以跳过内容并在中添加其他可能很重要的内容
if(defined(\'DOING_AJAX\')){
// AJAX only stuff...