【发布时间】:2016-02-15 05:12:59
【问题描述】:
我有一个简单的页面(索引),其中有一个充满 cmets 的 div。它下面还有一个表单,用户可以在其中输入他们的姓名和消息,然后单击提交以发表评论。我有一个 php 页面来处理进入 MySQL 的过程,并在索引页面上使用 AJAX 来更新 cmets 而无需刷新。我的代码在 Chrome 上运行,但在 Firefox 上运行不同。
在 Firefox 上,我需要输入两次完全相同的数据才能将其加载到数据库中一次。第一次它什么也不做,如果我输入不同的数据它仍然什么都不做(因为那将是该数据的第一次),但如果我输入相同的数据两次,那么它会正确插入mysql,ajax会正确更新评论 div。
这是 index 上的脚本和 html:
<div id="comments">
<ul>
<?php while($row = mysqli_fetch_assoc($results)) : ?>
<li id='comment'><span>
<?php echo $row['time']; ?> - </span><strong>
<?php echo $row['user'];?>: </strong>
<?php echo $row['msg']; ?>
</li>
<?php endwhile; ?>
</ul>
</div>
<script>
$(document).ready(function() {
$(".comment-btn").click(function() {
var user = $("#user").val();
var msg = $("#msg").val();
$.post("process.php",{user:user,msg:msg},function(data){
$("#comments").html(data);
});
});
});
</script>
<div class="input">
<?php if(isset($_POST['error'])) : ?>
<div class="comment-error"><?php echo $_POST['error']; ?></div>
<?php endif; ?>
<form id="myForm">
<input id="user" type="text" name="user" placeholder="Enter Your Name" />
<input id="msg" style="float: right;" type="text" name="msg" placeholder="Enter Your Message" /><br>
<input class="comment-btn" type="submit" name="submit" value="Post Comment" />
</form>
</div>
这里是process.php:
<?php
include 'comments.php'; // just contains the connection
?>
<?php
$user = mysqli_real_escape_string($con, $_POST['user']);
$msg = mysqli_real_escape_string($con, $_POST['msg']);
// set timezone
date_default_timezone_set('America/Los_Angeles');
$time = date('h:i:s a',time());
if(!isset($user) || $user == '' || !isset($msg) || $msg == '') {
echo "Please fill in your name and a comment";
exit();
} else {
$query = "INSERT INTO comment (user, msg, time)
VALUES ('$user', '$msg', '$time')";
if(!mysqli_query($con, $query)) {
die('Error: '.mysqli_error($con));
} else {
$selectQ = "SELECT * FROM comment";
$results = mysqli_query($con, $selectQ);
echo "<ul>";
while($row = mysqli_fetch_assoc($results)) {
echo "<li id='comment'><span>";
echo $row['time']; echo "- </span><strong>";
echo $row['user']; echo ": </strong>";
echo $row['msg'];
echo "</li>";
}
echo "</ul>";
exit();
}
}
?>
同样,这只发生在 Firefox 上。在 Chrome 中工作。非常感谢任何帮助
【问题讨论】:
-
第一次尝试使用 firefox 时,您在控制台的网络选项卡中得到了什么? (发送和响应)
-
@DelightedD0D 第一次唯一的事情(这是相关的)我得到的是来自localhost/adamallard/… 的 GET 在第二次尝试我从 process.php 得到 POST
-
不影响您当前的问题,但在循环中执行
<li id='comment'>会创建n数量的id='comment',这是无效的,因为ids 是唯一的。 -
试一试:- ` $(".comment-btn").click(function(e) { e.preventDefault();`
-
如果你想对
$("#comment")做点什么,唯一的问题就是。链接到特定评论、删除特定评论、突出显示特定评论等。在每种情况下,它都不知道您引用的是哪个id="comment"。在您的特定代码中不是问题,但对于 SO 上的其他帖子而言。这就是为什么防止无效 DOM 总是好的做法。在这种情况下,只需更改为class="comment"即可。
标签: php jquery mysql ajax firefox