我试图了解jquery,特别是使用ajax在mysql表中插入和显示数据。
我一直在尝试使用此代码插入并显示mysql数据库中的记录。我现在试图让它在div中显示成功消息,其中包含id" info"同时还显示所有记录。我似乎只做一个,但从来没有。非常感谢。
form.php的
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function showComment(){
$.ajax({
type:"post",
url:"process_ajax.php",
data:"action=showcomment",
success:function(data){
$("#comment").html(data);
}
});
}
showComment();
$("#button").click(function(){
var username=$("#username").val();
var review=$("#review").val();
$.ajax({
type:"post",
url:"process_ajax.php",
data:"username="+username+"&review="+review+"&action=addcomment",
success:function(data){
$("#info").html(data);
}
});
});
});
</script>
</head>
<body>
<form>
Username : <input type="text" name="username" id="username"/>
</br>
Review : <input type="text" name="review" id="review" />
</br>
<input type="button" value="Send Comment" id="button">
</form>
<div id="info" />
<ul id="comment"></ul>
</body>
</html>
Process_ajax.php
<?php
include_once("db_conx.php");
$action=$_POST["action"];
if($action=="showcomment"){
$show="Select * from user_reviews ORDER by date desc";
$result = $db_conx->query($show);
while($row=mysqli_fetch_array($result)){
echo "<li><b>$row[username]</b> : $row[review]</li>";
}
}
else if($action=="addcomment"){
$username= ($_POST['username']);
$review= ($_POST['review']);
$stmt = $db_conx->prepare('INSERT user_reviews SET username = ?, review=?');
$stmt->bind_param('ss', $username, $review);
$stmt->execute();
if ($stmt->errno) {
echo "There was an error in saving your review. Please try again." . $stmt->error;
}else{
echo "Your review has been saved";
}
}
?>
答案 0 :(得分:0)
将记录数据保存为数组,将消息保存为普通var并创建一个json:
$list = '';
while($row=mysqli_fetch_array($result)){
$list .= "\n<li><b>$row[username]</b> : $row[review]</li>";
}
if ($stmt->errno) {
$msg = "There was an error in saving your review. Please try again." . $stmt->error;
}else{
$msg = "Your review has been saved";
}
echo json_encode(["list"=>$list, "msg"=>$msg]);
请记住将dataType放入Ajax:
type:"post",
dataType: "json"
然后在您的成功功能中,您可以访问变量:data.list
和data.msg