使用AJAX获取帖子数据

I'm trying to pull content from Wordpress posts AJAX.

I have included my efforts so far below.

Loaded scripts.

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' ) ) );

JavaScript

jQuery(document).ready(function($) {

  $('.ajax 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) {
        console.log(data);
      }
    });     

    return false;

  });

});

Here I set up my action. How to encode post data as JSON and return?

add_action('wp_ajax_nopriv_ajax_request', 'ajax_handle_request');
add_action('wp_ajax_ajax_request', 'ajax_handle_request');

function ajax_handle_request(){
}

Use the functions wp_send_json_success and wp_send_json_error to return the Ajax request result.

Both of them use wp_send_json, which takes care of the header, JSON encoding and echoing, and to die.

Also, you should send a nonce when localizing the script:

array(
    'url'   => admin_url( 'admin-ajax.php' ),
    'nonce' => wp_create_nonce( "my_long_unique_string_name" ),
)

And check it within wp_ajax_* action callback:

check_ajax_referer( 'my_long_unique_string_name', 'nonce' );

Example: https://wordpress.stackexchange.com/a/106436/12615

Update:

I'm seeing activity on this post, and it's very old.

Please use the WP REST API instead: https://developer.wordpress.org/rest-api/


I was able to figure this out by setting global $post variable.

Then by encoding the $response.

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;
}

Using jQuery to retrieve the data and output.

jQuery(document).ready(function($) {

  $('.ajax 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) {
        console.log(data['post']);
      }
    });     

    return false;
  });
});