wordpress文件管理ajax有一个奇怪且令人沮丧的行为。php,当我发出ajax请求时,它返回一个错误的404错误请求。
function rp_add_header() {
if (is_single() || is_page()) {
// include the jquery Ajax/form validation javascript file
wp_enqueue_script( \'ajax-script\', plugin_dir_url(__FILE__).\'rp-script.js\', array(\'jquery\'), 1.0 ); // jQuery will be included automatically
// create the three Ajax variables used in your template file
wp_localize_script( \'ajax-script\', \'ajax_object\', array(
\'ajaxurl\' => admin_url( \'admin-ajax.php\' ),
\'errorEmpty\' => __( \'You need to select one of the options.\' )
)
);
add_action( \'wp_ajax_ajax_action\', \'ajax_action_stuff\' ); // ajax for logged in users
add_action( \'wp_ajax_nopriv_ajax_action\', \'ajax_action_stuff\' ); // ajax for not logged in users
}
}
add_action(\'wp_head\',\'rp_add_header\',1);
function ajax_action_stuff() {
global $mail_report_to;
$resp[\'status\'] = \'error\';
$resp[\'errmessage\'] = \'\';
if (!empty($_POST[\'report-msg\'])) {
$report_msg = $_POST[\'report-msg\'];
$report_url = $_POST[\'posturl\'];
$subject = \'Post report[\'.get_option(\'blogname\').\']\';
$header = \'From: \'.get_option(\'blogname\').\' <\'.get_option(\'admin_email\').\'>\' . "\\r\\n";
$message = \'
Someone has reported a post:
Report: \'.$report_msg.\'
Post URL: \'.$report_url.\'
Visitor IP: \'.$_SERVER[\'REMOTE_ADDR\'].\'
Date/time: \'.date(\'Y-m-d H:i:s\');
if ( wp_mail($mail_report_to, $subject, $message, $header) ) {
$resp[\'status\'] = \'success\';
$resp[\'errmessage\'] = \'Your report is submitted, thanks.\';
} else {
$resp[\'errmessage\'] = \'Something went wrong, please try again later.\';
}
} else {
$resp[\'errmessage\'] = \'Please select one of the options.\';
}
header( "Content-Type: application/json" );
echo json_encode($resp);
exit;
}
我已经删除了所有插件,问题依然存在,你有什么想法吗?
最合适的回答,由SO网友:Jacob Peattie 整理而成
您只是在内部挂接AJAX响应wp_head()
:
function rp_add_header() {
if (is_single() || is_page()) {
// etc.
add_action( \'wp_ajax_ajax_action\', \'ajax_action_stuff\' ); // ajax for logged in users
add_action( \'wp_ajax_nopriv_ajax_action\', \'ajax_action_stuff\' ); // ajax for not logged in users
}
}
add_action(\'wp_head\',\'rp_add_header\',1);
但是
wp_head
无法运行
admin-ajax.php
, 所以你的回调永远不会被钩住。您需要将这些挂钩移出该功能:
function rp_add_header() {
// etc.
}
add_action( \'wp_head\', \'rp_add_header\', 1 );
function ajax_action_stuff() {
// etc.
}
add_action( \'wp_ajax_ajax_action\', \'ajax_action_stuff\' ); // ajax for logged in users
add_action( \'wp_ajax_nopriv_ajax_action\', \'ajax_action_stuff\' ); // ajax for not logged in users