如何正确编写ajax分页代码?

时间:2018-11-19 02:54:24

标签: javascript php ajax wordpress

对于编码人员和AJAX爱好者,我有一个问题需要解决。 我有一些代码示例javascript,jquery和php。

mvn archetype:generate

functions.php

  function find_page_number( element ) {
    element.find('span').remove();
        return parseInt( element.html() );
    }

    $(document).on( 'click', '#PaginationExample a', function( event ) {
        event.preventDefault();

        page = find_page_number( $(this).clone() );
$.ajax({
    url: ajaxpagination.ajaxurl,
    type: 'post',
    data: {
        action: 'ajax_pagination',
        query_vars: ajaxpagination.query_vars,
        page: page
    },
    beforeSend: function() {
        $('#showcase').find( 'article' ).remove();
        $('#showcase nav').remove();
        $(document).scrollTop();
        $('#showcase').append( '<div class="page-content" id="loader">Loading New Posts...</div>' );
    },
    success: function(html ) {
        $('#showcase').empty();
        $('#showcase').append(html );
        },

        })
    })
})(jQuery);

html部分

add_action( 'wp_ajax_nopriv_ajax_pagination', 'ajax_pagination' );
add_action( 'wp_ajax_ajax_pagination', 'ajax_pagination' );

function ajax_pagination() {
$query_vars = json_decode( stripslashes( $_POST['query_vars'] ), true );

    $query_vars['paged'] = $_POST['page'];


    $posts = new WP_Query( $query_vars );
    $GLOBALS['wp_query'] = $posts;

    add_filter( 'editor_max_image_size', 'my_image_size_override' );

    if( ! $posts->have_posts() ) { 
        get_template_part( 'content', 'none' );
    }
    else {
        while ( $posts->have_posts() ) { 
            $posts->the_post();
            get_template_part( 'content', get_post_format() );
        }
    }
    remove_filter( 'editor_max_image_size', 'my_image_size_override' );

    the_posts_pagination( array(
        'prev_text'          => __( 'Previous page', 'webisawesome' ),
        'next_text'          => __( 'Next page', 'webisawesome' ),
        'before_page_number' => '<ul id="PaginationExample">' . __( 'Page', 'webisawesome' ) . ' </ul>',
    ) );

    wp_die();
}

function my_image_size_override() {
    return array( 825, 510 );
}


function add_myjavascript(){
  wp_enqueue_script( 'ajax-pagination', get_template_directory_uri(). '/js/ajax-pagination.js', array( 'jquery' ), '1.0', true  );
 global $wp_query;
  wp_localize_script( 'ajax-pagination', 'ajaxpagination', array(
    'ajaxurl' => admin_url( 'admin-ajax.php' ),
    'query_vars' => json_encode( $wp_query->query )
));

  }
  add_action( 'init', 'add_myjavascript' );

那么谁能回答为什么单击页面后它返回0?有人知道什么可能是错误的,什么是使代码正常工作和页面张贴所缺少的?我的网站基于https://www.webisawesome.com/category/services基于WordPress :)如果您需要有关它的更多信息,请告诉我。谢谢大家!

0 个答案:

没有答案