我也面临同样的问题。
我想使用我自己的端点,而不是管理ajax端点,因为我已经重写了填充运行ajax操作所需的所有变量的规则。
因此,使用(如上所述in the codex)
jQuery(document).ready(function($) {
var data = {
\'action\': \'my_action\',
\'whatever\': ajax_object.we_value // We pass php values differently!
};
jQuery.post(ajax_object.ajax_url, data, function(response) {
alert(\'Got this from the server: \' + response);
});
});
以及
add_action( \'wp_ajax_my_action\', \'my_action\' );
add_action( \'wp_ajax_nopriv_my_action\', \'my_action\' );
只是让我的代码更复杂。
我最终做了这件事,似乎奏效了:
jQuery.ajax({
type: "post",
url: MYCUSTOMENDPOINT?ajax_action,
dataType: \'json\',
...
结合:
add_action( \'init\', \'rewrite_rules\');
add_filter( \'template_include\',\'handle_ajax_action\');
function rewrite_rules(){
add_rewrite_tag(
\'%ajax_action%\',
\'([^&]+)\'
);
}
function handle_ajax_action($template){
$success = null;
// since the "ajax" query variable does not require a value, we need to check for its existence
if ( !$action = get_query_var( \'ajax_action\' ) ) return $template; //ajax action does not exists
$result = array(
\'input\' => $_REQUEST,
\'message\'=> null,
\'success\'=> null,
);
$success = ...
if ( is_wp_error($success) ){
$result[\'success\'] = false;
$result[\'message\'] = $success->get_error_message();
}else{
$result[\'success\'] = $success;
}
header(\'Content-type: application/json\');
send_nosniff_header();
header(\'Cache-Control: no-cache\');
header(\'Pragma: no-cache\');
wp_send_json( $result );
}