javascript - 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 代码中遗漏了一些东西,但我不知道是什么。
有人可以就这个问题提出建议吗?
提前致谢。
解决方案
错误在您的 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
推荐阅读
- flutter - 在 Flutters 列表视图构建器中切换单个项目的活动
- elasticsearch - 在术语查询中包含多个变量并向它们添加权重以定义输出
- webpack - 如何将 NextJS 项目捆绑到一个文件中
- javascript - 我怎样才能有一个静态集合
- docker - docker login 错误:来自守护进程的错误响应:不支持路径 /v1.40/auth
- r - 想要删除重复的行,但所有行都被删除
- php - Laragon 中的 url 有问题。www.localhost/admin 不起作用,但 www.localhost/index.php/admin 工作正常
- c# - 在加载表单 C# 时获取 NullReferenceException
- rust - Rust:使用 ndarray-linalg 和 ndarray 板条箱的问题
- python - 在jetson nano上为python2.7安装boto3