PHP开发 发表评论功能教程之PHP页面
先来看PHP读取和生成JSON数据的server.php代码。

代码如下
<?php
header("Content-type:text/html;charset=utf-8");    //设置编码
$conn=mysqli_connect("localhost","root","root","comments");
mysqli_set_charset($conn,"utf8");
$sql="SELECT * from comments";
$que=mysqli_query($conn,$sql);
while($row=mysqli_fetch_array($que)){
      $comments[] = array("id"=>$row[id],"user"=>$row[user],"comment"=>$row[comment],"addtime"=>$row[addtime]);
}
echo json_encode($comments);
?>注意:你的PHP版本应该是5.2以上才能使用json_encode函数。
comments.php 代码
comment.php接收前台ajax提交过来的昵称和评论内容参数,判断参数的合法性,然后将数据插入到数据库中,如果成功,则输出1,返回给前台jQuery处理。
<?php
header("Content-type:text/html;charset=utf-8");    //设置编码
$user = htmlspecialchars(trim($_POST['user']));
$txt = htmlspecialchars(trim($_POST['txt']));
$time = date("Y-m-d H:i:s");
if(empty($user)){
   echo "昵称不能为空!";
   exit;
}
if(empty($txt)){
   echo "评论内容不能为空!";
   exit;
}
$conn=mysqli_connect("localhost","root","root","comments");
mysqli_set_charset($conn,"utf8");
$sql="insert into comments(user,comment,addtime)values('$user','$txt','$time')";
$que=mysqli_query($conn,$sql);
if($que)  echo "1";
?>我们将我们的HTML页面跟PHP代码组合起来,就能实现我们的评论功能了
本例使用简单容易的代码诠释了轻量、高效的jQuery结合PHP的ajax运作机制,当然这只是一个基础的例子,jQuery还能做很多事情,留给大家去尽情发挥吧。
 
			 
									 
									 
									 
									 
									 
									 
									 
									 
									 
									 
									 
									 
								 
								
 
								

 
  
             
        
依然范特西
不行啊
7年前 添加回复 2