如何不刷新页面更新PHP内容?实现点击加载更多评论无刷新效果
你当前页面刷新的原因是点击按钮触发了form表单的默认提交行为,浏览器会重新加载整个页面,我们通过AJAX异步请求后台数据、直接追加新评论到现有页面的方案就能实现无刷新加载,改动很小,适合初学者实现:
实现步骤
1. 新建独立的评论数据接口
新建get_more_comments.php文件,专门处理加载更多的请求,代码如下:
<?php // 这里先引入你原页面中数据库连接配置文件、以及username_grabber函数所在的文件,保证能正常调用数据库和工具函数 // 接收前端传递的当前已加载评论数量 $current_num = (int)$_POST['current_num']; // 这里复制你原页面中获取$com_elements的评论查询逻辑,保证拿到全量评论数据 $total_num = count($com_elements[0]); $return = []; // 每次加载1条评论,可自行调整加载数量 $load_count = 1; $end_index = min($current_num + $load_count, $total_num); // 组装需要返回的单条评论HTML for ($i = $current_num; $i < $end_index; $i++) { $return['html'][] = ' <div class="comment_bar mb-5"> <div class="card border-light shadow-sm"> <div class="card-body"> <h5 name="username">'.username_grabber($com_elements[1][$i],$con).'</h5> <hr> </div> <div class="card-text"> <p>'.$com_elements[3][$i].'</p> </div> </div> </div> '; } // 标记是否还有更多评论、更新当前已加载数量 $return['has_more'] = $end_index < $total_num; $return['new_current'] = $end_index; // 以JSON格式返回给前端 header('Content-Type: application/json'); echo json_encode($return); ?>
2. 修改原页面的展示代码
调整原页面的结构,去掉表单、增加评论列表容器,修正重复ID的问题:
<?php $num = count($com_elements[0]); $num_lim = 2; // 默认首次加载2条评论 ?> <?php if(isset($com_elements)):?> <!-- 新增评论列表容器,方便后续追加内容 --> <div id="comment_list"> <?php for ($i=0; $i < $num_lim; $i++):?> <!-- 把重复的id="comment_bar"改成class,id在页面中不能重复 --> <div class="comment_bar mb-5"> <div class="card border-light shadow-sm"> <div class="card-body"> <h5 name="username"><?php echo username_grabber($com_elements[1][$i],$con);?></h5> <hr> </div> <div class="card-text"> <p><?php echo $com_elements[3][$i];?></p> </div> </div> </div> <?php endfor?> </div> <div> <!-- 去掉form表单,直接用按钮,用自定义属性存储当前已加载的评论数量 --> <button id="more_comments" class="form-control border-light" data-current="<?php echo $num_lim;?>"> More comments </button> </div> <?php endif?>
3. 增加JS实现异步加载
在页面底部(</body>标签之前)加入原生JS代码,不需要引入额外框架:
document.getElementById('more_comments').addEventListener('click', function() { const loadBtn = this; const currentCount = parseInt(loadBtn.dataset.current); // 发起AJAX请求 const xhr = new XMLHttpRequest(); xhr.open('POST', 'get_more_comments.php'); xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xhr.onload = function() { if (xhr.status === 200) { const res = JSON.parse(xhr.responseText); // 把新评论追加到列表末尾 res.html.forEach(commentHtml => { document.getElementById('comment_list').insertAdjacentHTML('beforeend', commentHtml); }); // 更新已加载数量标记 loadBtn.dataset.current = res.new_current; // 没有更多评论时隐藏加载按钮 if (!res.has_more) { loadBtn.style.display = 'none'; } } }; // 传递当前已加载数量参数 xhr.send('current_num=' + currentCount); });
注意事项
- 请务必补全
get_more_comments.php中的数据库连接和评论查询逻辑,和你原页面的查询逻辑保持一致即可 - 若
get_more_comments.php和原页面不在同一目录,需要修改JS请求里的文件路径为正确的相对/绝对路径
内容的提问来源于stack exchange,提问作者salluc 1
相关产品推荐
相关产品推荐

