使用 AJAX 获取帖子数据

hyp*_*ive 3 ajax wordpress jquery

我正在尝试从 Wordpress 帖子 AJAX 中提取内容。

我已经将我的努力包括在下面。

加载的脚本。

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' ) ) );
Run Code Online (Sandbox Code Playgroud)

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;

  });

});
Run Code Online (Sandbox Code Playgroud)

在这里,我设置了我的操作。如何将帖子数据编码为 JSON 并返回?

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

function ajax_handle_request(){
}
Run Code Online (Sandbox Code Playgroud)

hyp*_*ive 6

更新:

我在这个帖子上看到了活动,它已经很旧了。

请改用 WP REST API:https : //developer.wordpress.org/rest-api/


我能够通过设置全局 $post 变量来解决这个问题。

然后通过对 $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;
}
Run Code Online (Sandbox Code Playgroud)

使用 jQuery 检索数据和输出。

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;
  });
});
Run Code Online (Sandbox Code Playgroud)