【发布时间】:2021-12-05 14:06:08
【问题描述】:
我在一个 WorPress 网站上工作,我希望我的页面上只有 4 个帖子,并使用 ajax 在其他帖子之间导航。
我有我的 front-page.php(只是尝试的代码):
<section>
<button type="button" name="button" id="btn_next">+</button>
<button type="button" name="button" id="btn_pre">-</button>
<div class="" id="result"></div>
<div class="" id="offset"></div>
</section>
我有我的 ajax.js
jQuery(document).ready(function($){
$("#btn_next").click(function(){
var off = $('#offset').html();
data_ajax(1);
})
$("#btn_pre").click(function(){
data_ajax(-1);
});
function data_ajax(new_offset){
$.ajax({
url: ajaxObject.url,
dataType: 'json',
method: 'POST',
data: {
action : 'ajax_agenda',
},
success: function(responseText){
console.log("result : " + JSON.stringify(responseText));
$("#result").html('<h3>résultats</h3>');
},
error: function(xhr, error, exception){
console.log(xhr);
console.log(error);
console.log(exception);
$("#result").html('<h3>Pas de résultats</h3>');
}
}); // fin ajax
}
});
和我在function.php中的函数
add_action('wp_ajax_ajax_agenda', 'ajax_agenda');
add_action('wp_ajax_nopriv_ajax_agenda', 'ajax_agenda');
function ajax_agenda(){
$final_array = array();
$args = array(
'posts_per_page' => 3, /* how many post you need to display */
'offset' => 1,
'orderby' => 'post_date',
'order' => 'DESC',
'post_type' => 'agenda', /* your post type name */
'post_status' => 'publish'
);
$query = new WP_Query($args);
$posts = $query->posts;
if($query->have_posts()){
$final_array["success"] = "true";
$final_array["results"] = $posts;
}
else{
$final_array["success"] = "false";
};
echo json_encode( $final_array );
die(); // Pour eviter les erreurs due au "die(0)"" prédrnt dans le fichier "admin-ajax.php"
};
但我没有到达使用 js 返回的数据 :( 我需要你的帮助。
泰
【问题讨论】:
-
你为什么要在
data_ajax调用中传递new_offset参数,然后在函数内部对传递的值完全不做任何事情? -
我没有戴上,因为我以后会处理它