【发布时间】:2018-07-05 04:40:45
【问题描述】:
我正在创建一个博客,我想通过 ajax 加载我的帖子,而不是分页,我做到了。
但问题是: 我对每个帖子都有类似 ajax 的系统,但它只适用于未加载 ajax 的帖子。
-- 处理请求的PHP方法:
public function load_more(){
$offset = $this->input->post('loaded_count' , true) ? : 0 ;
// for those who don't know codeigniter the line above is equal to $_POST['loaded_count']
$posts = $this->mod->get_posts($offset);
// gets posts array from database
include_once "./application/views/inc/show-posts.php";
}
在 show-posts.php 文件中,我有我的帖子模板,它在 $posts 变量上执行 foreach 循环。
-- 用于加载帖子的 Ajax:
$(".load-more-btn").click(function(){
var $this = $(this);
var $posts_cont = $(".posts-container");
var $loadedPostsCount = $this.attr('data-ppp');
$.ajax({
url : "http://localhost/bona/ajax/load_more" ,
type : 'post' ,
data : {loaded_count : $loadedPostsCount} ,
success : function(resp){
$posts_cont.append(resp);
},
error : function(xhr){
alert("error");
console.log(xhr);
}
});
});
-- 点赞帖子的Ajax
$(".like-post").click(function(){
var $postID = $(this).attr("data-class");
var $this = $(this).find(".like-holder");
$.ajax({
url : "http://localhost/bona/ajax/add_like') ?>",
type : "post" ,
data : { like_id : $postID } ,
success : function (resp,s,x){
$this.text(resp);
} ,
error : function(xhr){
alert("error");
console.log(xhr);
}
});
});
1 : 我把这两个放在 $(document).ready() 事件中。
2:点击时我没有收到任何错误,看起来点击事件(喜欢)不会触发 ajax 加载的帖子。
3:我正在使用 Codeigniter
我认为 $(document).ready 导致了这个问题。
你觉得怎么样?
【问题讨论】:
-
我建议使用
id而不是class来执行点击事件等操作,所以<button id="like_post">Like</button>然后你的js 看起来像$("#like_post").click(function(){你也可以在表单提交上做$("#form_id_is_in_here").submit(function(e){ -
你的 show-posts.php 是什么样的?
-
这只是 $posts 数组的循环
标签: php jquery ajax codeigniter