接下来,我成功地将一个ajax对象传递到后端(JS中的脚本实际上并不重要,因为我已经很好地完成了):
add_action( \'wp_ajax_my_action\', \'my_action_callback\' );
add_action( \'wp_ajax_nopriv_my_action\', \'my_action_callback\' );
add_action( \'wp_enqueue_scripts\', \'theme_name_scripts\' );
add_shortcode(\'tagtest\', \'timezone\');
function theme_name_scripts() {
wp_enqueue_script( \'script-name\', plugins_url( \'/assets/js/timezone.js\', __FILE__ ), array(\'jquery\'), \'1.0.0\', true );
wp_localize_script( \'script-name\', \'MyAjax\', array(
\'ajaxurl\' => admin_url( \'admin-ajax.php\' ),
\'security\' => wp_create_nonce( \'my-special-string\' ),
));
}
function my_action_callback() {
$whatever = strval( $_POST[\'whatever\'] );
echo $whatever;
return $whatever;
wp_die();
}
但我有一个时区函数,它是add\\u shortcode挂钩的函数。我需要从timezone函数中的\\u action\\u回调中获取变量$whatever。我该怎么做?function timezone(){
$whatever = //Here I need the result from my_action_callback function
}
以防万一,这里是我的JS脚本和一个确保对象成功通过的图像jQuery(document).ready(function($) {
var data = {
action: \'my_action\',
security : MyAjax.security,
whatever: \'Hello there\'
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
$.post(MyAjax.ajaxurl, data, function(response) {
alert(\'Here is: \' + response);
return response;
});
});
以下是XHR响应:action: my_action
security: f1860eab4b
whatever: Hello there
我在add\\u操作回调中获取此对象时没有出现问题正如我之前所说,我唯一需要的,而且我还没有让它工作的是在timezone函数中获得$whatever(timezone是add\\u shortcode的函数),我如何实现这一点?提前谢谢。