【发布时间】:2018-12-09 18:04:15
【问题描述】:
尝试请求用户发布的帖子并根据用户的请求加载更多帖子。 在控制台中发出 ajax 请求时出现意外结束 JSON 输入错误。
Javascript
$("#ajax_load_more").click(function(){
$.ajax({
type: "GET",
url: "action.php?action=morePosts",
success: function(response){
var result = $.parseJSON(response);
console.log(result);
}
});
});
向以下代码发出请求。 $_SESSION['posts']) 存储要在会话中加载的帖子数。
if($_GET['action']=="morePosts"){
if(isset($_SESSION['posts'])){
$_SESSION['posts'] = $_SESSION['posts'] + 4;
echo fetchAllPosts($_SESSION['posts']);
} else if(isset($_SESSION['posts'])&& $_SESSION['posts']>4){
$_SESSION['posts'] = 4;
}
}
请求所有帖子的功能
function fetchAllPosts2($array_length){
$db = new db; //Class for database
$query = "SELECT * FROM `posts` ORDER BY `post_id` DESC LIMIT $array_length";
$result = $db::query($query);
$row = mysqli_fetch_all($result);
$post = array();
for($i=0; $i<$array_length; $i++){
if(!empty($row[$i])){
for($j=0;$j<count($row);$j++){
$post['id']=$row[$i][0];
$post['user_id']=$row[$i][1];
$post['title']=substr($row[$i][2], 0 ,75);
$post['text']=strip_tags(mb_substr($row[$i][3],0,50));
$post['image']=$row[$i][4];
$post['date']=$row[$i][5];
}
return json_encode($post);
}
elseif(empty($row[count($row)])){
return json_encode(array());
}
}
}
请提出更好的方法来实现此功能,
【问题讨论】:
-
您是否使用
session_start()和$_SESSION['post']初始化了会话?您是否检查过您在每个 AJAX 请求中访问的会话是否相同?
标签: javascript php jquery json