将此添加到函数中。php文件:
function my_action() {
$the_post_id = $_POST[\'id\'];
$output = json_encode( get_post( $the_post_id ) );
header(\'Content-Type: application/json\');
echo $output;
wp_die();
}
add_action(\'wp_ajax_my_action\', \'my_action\');
add_action(\'wp_ajax_nopriv_my_action\', \'my_action\');
将脚本排队:
function add_scripts() {
wp_enqueue_script( \'app\', get_template_directory_uri() . \'/assets/js/build.min.js\', array(), \'1.0.0\', true );
wp_localize_script( \'app\', \'my_ajax_object\', array( \'ajaxurl\' => admin_url( \'admin-ajax.php\' ) ) );
}
add_action( \'wp_enqueue_scripts\', \'add_scripts\' );
js文件中的AJAX调用:
$.ajax({
url : my_ajax_object.ajaxurl,
type: \'POST\',
data : {
\'action\' : \'my_action\',
\'id\' : 214 // And whatever else you need to pass on ...
}
}).done(function ( response ) {
}).fail(function ( err ) {
});