我已经搜索了很多,但仍然没有找到任何解决方案。我想在提交帖子评论后调用ajax操作。我怎样才能用WordPress做到这一点?
没有代码,我无法自己用代码给你以下步骤:
-
跟踪触发注释提交的事件以及它发生在哪个 DOM 元素上。
-
在事件处理程序中,使用
jQuery.ajax
将 XMLHTTPRequest 发送到服务器。 -
确保以 Wordpress 的方式创建 ajax 调用,因此通过向
wp-admin/admin-ajax.php
发送请求并将逻辑置于functions.php
下。添加die()
函数。
我会用WordPress过滤器过滤评论。您可能根本不需要 AJAX 请求。但我不确定为什么需要 AJAX。要了解有关此筛选器的更多信息。
function preprocess_comment_handler( $commentdata ) {
//some code
return $commentdata;
}
add_filter( 'preprocess_comment' , 'preprocess_comment_handler' );
如果你确实需要AJAX,这里是让它在WordPress中运行的方法。你需要使用 wp_localize_script() 让你的 AJAX 到 admin-ajax.php。
//add wp_localize_script to your functions.php
//make sure to enqueue the js file you are writing to and it's dependencies
function acarter_enqueue_scripts() {
wp_enqueue_script( 'jquery' );
wp_enqueue_script('your-script', get_template_directory_uri() . '/js/theme.js');
wp_localize_script('your-script', 'your_script_vars', array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
)
);
}
add_action( 'wp_enqueue_scripts', 'acarter_enqueue_scripts' );
//do your AJAX call in the file you just enqueued
jQuery( document ).ready( function($) {
//Ajax Form Processing
var $form = $( '#button' )
$form.submit( function (e) {
e.preventDefault();
$.ajax({
type: '',
url: your_script_vars.ajaxurl,
data: {
action: 'function_name_of_the_callback',
//key : values of stuff you want in the php callback
},
dataType: 'json',
success: function (response) {
if ( true === response.success ) {
console.log( 'success!!' );
});
} else if ( false === response.success && response.data ) {
window.alert( 'doing it wrong' );
}
}
});
});
});
您也许可以将数据发送到上述过滤器,从而使用过滤器作为回调,但是,我从未尝试过。至少你会知道如何在WordPress中设置AJAX。