使用AJAX获取发布数据

时间:2013-08-18 22:27:52

标签: jquery ajax wordpress

我正在尝试学习AJAX和JSON,我在寻找合适的资源方面遇到了一些麻烦。我还有很多问题,所以我主要是寻找资源。

我的目标是从wordpress帖子中提取内容。我试着寻找教程和讨论,但我找到的解决方案对我不起作用或者我不喜欢,所以我不能正确理解我做错了什么。

到目前为止,我已将我的努力包括在内,但这不是我的主要问题

已加载的脚本。

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;

  });

});

我在这里设置了我的动作。 如何编码JSON并返回要使用的帖子数据?

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

function ajax_handle_request(){
}

2 个答案:

答案 0 :(得分:4)

我能够通过设置全局$ post来获得$ 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;
}

使用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;
  });
});

答案 1 :(得分:0)

使用函数wp_send_json_successwp_send_json_error返回Ajax请求结果。

它们都使用wp_send_json,它负责标题,JSON编码和回显,并且会死掉。

此外,您应该在本地化脚本时发送一个nonce:

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

并在wp_ajax_*动作回调中查看:

check_ajax_referer( 'my_long_unique_string_name', 'nonce' );

示例:https://wordpress.stackexchange.com/a/106436/12615

相关问题