首页无刷新创建帖子功能失效问题求助(附代码)
解决无刷新创建帖子的AJAX问题
我来帮你排查并修复这个无刷新提交表单的问题,你的代码里有几个关键的小问题,咱们一步步来修正:
1. 阻止表单默认提交行为
你的按钮是type="submit",点击时会触发浏览器默认的表单提交(直接刷新页面),这是导致无刷新功能失效的核心原因之一。先修改按钮的点击事件,阻止默认行为:
<button class="btn-ajouter" type="submit" onclick="event.preventDefault(); get();" name="ajouter" value="ajouter">ajouter</button>
2. 修复AJAX请求的多处错误
你的AJAX代码存在数据未传递、语法错误、容器ID不匹配等问题,修正后的完整函数如下:
function get(){ // 再次确保阻止默认提交行为 event.preventDefault(); // 获取并验证表单输入 const title = document.querySelector('.title-input').value; const text = document.getElementById('text').value; if(!title.trim() || !text.trim()) { alert('请填写完整的标题和内容'); return; } let result; if(window.XMLHttpRequest) { result = new XMLHttpRequest(); } else { result = new ActiveXObject('Microsoft.XMLHTTP'); } result.onreadystatechange = function() { if(result.readyState === 4) { if(result.status === 200) { // 注意:页面展示容器是#result,不是#allpost,这里要对应 document.getElementById('result').innerHTML = result.responseText; // 提交成功后清空表单 document.querySelector('.posting').reset(); } else { alert('请求失败,请稍后重试'); } } }; // 改用异步请求(第三个参数设为true,同步请求会阻塞浏览器) result.open('POST', 'accueil.php', true); // 修正请求头的空格错误 result.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // 传递表单数据,用encodeURIComponent避免特殊字符乱码 result.send(`title=${encodeURIComponent(title)}&text=${encodeURIComponent(text)}&ajouter=ajouter`); }
3. 修复PHP的SQL插入参数顺序错误
你的PHP代码里,SQL插入的参数顺序搞反了!SQL定义的是(title_post, post),但你把内容传给了标题字段,标题传给了内容字段,修正如下:
// 原错误代码:$stmt->execute(array($texte,$title)); // 修正后: $stmt->execute(array($title, $texte));
另外建议优化PHP逻辑,区分AJAX请求和普通页面请求,避免返回多余内容:
<?php // 假设数据库连接$connect已初始化 if(isset($_POST['ajouter']) && !empty($_POST['text']) && !empty($_POST['title']) ) { $texte = htmlspecialchars($_POST['text']); $title = htmlspecialchars($_POST['title']); $stmt=$connect->prepare('INSERT INTO publications(title_post,post) VALUES(?,?) '); $stmt->execute(array($title, $texte)); } // 如果是AJAX请求,只返回帖子列表 if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') { // 按最新发布排序更合理 $stmt = $connect->query('SELECT * FROM publications ORDER BY id DESC'); while($row=$stmt->fetch() ) { echo '<div class="post-item">'; echo '<h3>' . $row['title_post'] . '</h3>'; echo '<p>' . $row['post'] . '</p>'; echo '</div>'; } exit; } ?>
4. 移除不必要的表单属性
因为你的表单没有文件上传需求,所以可以去掉enctype="multipart/form-data",避免干扰AJAX的数据传递:
<form class="posting" method="POST"> <!-- 表单输入项不变 --> </form>
把这些修改全部应用后,打开浏览器开发者工具(F12)的Network标签,测试提交功能,就能看到AJAX请求正常发送、数据正确插入,页面也不会刷新,帖子列表会自动更新。
内容的提问来源于stack exchange,提问作者zikoo
相关产品推荐
相关产品推荐

