我正在尝试获取主页上帖子的ID。到目前为止,我的编码是
wp_enqueue_script( \'my-ajax-request\', get_stylesheet_directory_uri() . \'/js/ajax.js\', array( \'jquery\' ) );
wp_localize_script( \'my-ajax-request\', \'MyAjax\', array( \'ajaxurl\' => admin_url( \'admin-ajax.php\' ) ) );
add_action(\'wp_ajax_nopriv_ajax_request\', \'ajax_handle_request\');
add_action(\'wp_ajax_ajax_request\', \'ajax_handle_request\');
function ajax_handle_request(){
$postID = $_POST[\'id\'];
if (isset($_POST[\'id\'])){
$post_id = $_POST[\'id\'];
}else{
$post_id = "";
}
global $post;
$post = get_post($postID);
$response = array(
\'sucess\' => true,
\'post\' => $post,
\'id\' => $postID ,
);
// generate the response
print json_encode($response);
// IMPORTANT: don\'t forget to "exit"
exit;
}
和我的jquery
jQuery(document).ready(function($) {
$(\'h1.entry-title a\').click(function(event) {
event.preventDefault();
var id = $(this).data(\'id\');
$.ajax({
type: \'POST\',
url: MyAjax.ajaxurl,
data: {\'action\' : \'ajax_request\', \'id\': id},
dataType: \'json\',
success: function(data) {
alert(data[\'post\']);
}
});
return false;
});
});
但我得到的警报为Null,而不是post的id。