ajax 终端显示代码
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<div id="data-container">
<?php
// 初始加载的帖子
// if (have_posts()) :
// while (have_posts()) : the_post();
// get_template_part('template-parts/content', get_post_format());
// endwhile;
// endif;
?>
</div>
<button id="load-more">加载更多</button>
<script>
// ajax-load-more.js
jQuery(document).ready(function($) {
let page = 2; // 初始页码设置为2,因为第一页已经加载
let loading = false; // 防止重复加载
$('#load-more').click(function() {
if (!loading) {
loading = true;
$.ajax({
url: "/wp-admin/admin-ajax.php",
type: "POST",
data: {
action: 'load_more_data', // Action name
page: page,
nonce: my_ajax_object.nonce // Security nonce my_ajax_object.nonce
},
success: function(response) {
if (response.success) {
$('#data-container').append(response.data);
page++; // 增加页码
if (!response.data) {
$('#load-more').text('没有更多内容了').prop('disabled', true);
}
} else {
$('#load-more').text('没有更多内容了').prop('disabled', true);
}
loading = false; // 释放加载锁
},
error: function() {
$('#load-more').text('加载失败,请重试');
loading = false; // 释放加载锁
}
});
}
});
});
</script>
主题function 加载承接前端的请求
// 在 functions.php 文件中添加 Ajax 处理函数
// functions.php
function my_enqueue_scripts() {
wp_enqueue_script('ajax-script', array('jquery'), null, true);
wp_localize_script('ajax-script', 'my_ajax_object', array(
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('my_ajax_nonce') // Create a nonce for security
));
}
add_action('wp_enqueue_scripts', 'my_enqueue_scripts');
function load_more_data() {
// check_ajax_referer('my_ajax_nonce', 'nonce'); // Check the nonce for security
check_ajax_referer('my_ajax_nonce', 'nonce'); // Check the nonce for security
// 获取当前页码
$paged = isset($_POST['page']) ? intval($_POST['page']) : 2;
$query = new WP_Query(array(
'post_type' => 'post',
'paged' => $paged,
));
if ($query->have_posts()) :
ob_start(); // Start output buffering
while ($query->have_posts()) : $query->the_post();
// 使用模板部分来显示帖子内容
// get_template_part('template-parts/loop-article', get_post_format());
the_title()."<hr>";
endwhile;
$data = ob_get_clean(); // Get the buffered content
wp_send_json_success($data); // 发送成功响应
else :
wp_send_json_error(); // 发送错误响应
endif;
wp_reset_postdata();
wp_die();
}
add_action('wp_ajax_load_more_data', 'load_more_data');
add_action('wp_ajax_nopriv_load_more_data', 'load_more_data');
1173

被折叠的 条评论
为什么被折叠?



