首页 > 解决方案 > AJAX 加载更多功能乘以旧数据?

问题描述

我有一个 PHP 代码,可以从数据库中的 wordpress 帖子创建 JSON 数据。

我使用 AJAX 在我的 html 页面上加载这个 JSON。

以上工作正常。

现在我需要添加一个“加载更多”按钮,因此每次按下它时,我们都会加载另外 10 个帖子并将它们附加/添加到已经加载的帖子中,而无需删除旧帖子并重新添加它们。

所以这是我用于加载更多内容的 AJAX 代码:

var i = 0;
$(document).on("click", ".loadMoreBtn", function () {
    $.ajax({
        url: 'https://some-domain.com/index.php?t=' + mainCat + '&page=' + i + '',
        dataType: 'json',
        jsonp: 'jsoncallback',
        timeout: 5000,
        success: function (data, status) {

            if (!$.trim(data)) {

            }
            else {
            }

            $.each(data, function (pi, item) {

                var id = item.id;
                var img = item.img;
                var title = item.title;
                var date_added = item.date_added;

                var item = '' + title + '';

                $('.myDiv').before(item);
                i++;
            });

        },

        error: function () {
            //error handling////
        }
    });
});

这是我的 PHP 代码:

<?php
    header('Access-Control-Allow-Origin: *');
    header('Content-Type: application/json');
    $path = $_SERVER['DOCUMENT_ROOT'];
    include_once $path . '/wp-config.php';
    include_once $path . '/wp-load.php';
    include_once $path . '/wp-includes/wp-db.php';
    include_once $path . '/wp-includes/pluggable.php';

      $t = $_GET['t'];
      $page = $_GET['page'];
      $posts = get_posts(array(
      'posts_per_page' => $page, //add -1 if you want to show all posts
      'post_type' => 'post',
      'post_status' => 'publish',
      'tax_query' => array(
                  array(
                        'taxonomy' => 'category',
                        'field' => 'slug',
                        'terms' => $t //pass your term name here
                          )
                        ))
                       );



    $output= array();
    foreach( $posts as $post ) {

        $feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );

        $mysqldate = $post->post_date;
        $phpdate = strtotime( $mysqldate );
    $mysqldate = date( 'F d Y', $phpdate );
        // Pluck the id and title attributes
        $output[] = array( 'id' => $post->ID, 'title' => $post->post_title, 'date_added' => $mysqldate, 'img' =>$feat_image );
    }

    echo json_encode( $output );

当我单击“ Load More”按钮时,它的行为很奇怪!它基本上添加旧数据并乘以相同的数据并添加/加载一些新数据。

我知道我在我的 PHP 代码中遗漏了一些东西,但我不知道是什么。

有人可以就这个问题提出建议吗?

提前致谢。

标签: javascriptphpjqueryajaxwordpress

解决方案


错误在您的 wordpress 查询中。“posts_per_page”设置将加载多少帖子。将其设置为应该加载多少帖子,例如 12 或其他内容。

您要设置为 $page 参数的参数是“paged”。例如。$query = new WP_Query( array( 'paged' => 6 ) ); // page number 6

https://codex.wordpress.org/Class_Reference/WP_Query#Pagination_Parameters


推荐阅读