我创建了一个博客平台,我有一个ajax更新页面,我可以选择要显示的文章及其评论和添加评论。当我发表评论时,它会记录用户信息,已发表评论的文章,但不会将评论值存储在数据库中。这是代码:
<div align="center">
<h3>Comentarii:</h3>
<form method="POST">
<textarea rows="4" cols="50" name="comentariu" placeholder="Comenteaza">
</textarea><br>
<input type="submit" name="submit"><br>
<hr>
</form>
</div>
<?php
$comnou = $_POST['comentariu'];
$comuser = $_SESSION['user'];
$conadaugacom = mysqli_connect("localhost", "root", "", "blog");
$sqladaugacom = "insert into comentarii (continut_comentarii,
user_comentarii, articol_comentarii) values ('$comnou', '$comuser', '$ta')";
mysqli_query($conadaugacom, $sqladaugacom);
mysqli_close($conadaugacom);
?>
AJAX代码 - &gt;
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "getuser.php?q=" + str, true);
xmlhttp.send();
}
}
答案 0 :(得分:1)
确保在 POST 请求之前从表单序列化数据。
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div align="center">
<h3>Comentarii:</h3>
<form method="POST">
<textarea rows="4" cols="50" name="comentariu" placeholder="Comenteaza">
</textarea><br>
<input type="submit" name="submit"><br>
<hr>
</form>
</div>
Jquery的
<script>
$('input').submit(function(e){
e.preventDefault();
var data = $('form').serialize();
$.ajax({
url: 'your_url_to_post.php',
data: data,
success: function(response){
},
type: 'POST'
});
});
</script>
php文件
添加此行以检查 comentariu 非空
if(isset($_POST['comentariu'])){
$comentariu = $_POST['comentariu];
}