2012-05-20 4页 doc 92KB 12阅读
is_392653
暂无简介
昵称:
评论内容:
"+array["user"]+":"+array["comment"]+"" +array["addtime"]+"
"; comments.append(txt); }); }); }); 可以看出,需要通过$.each循环,读取JSON数据,因为生成的JSON数据有多条评论。当然你也可以使用for循环,但我更倾向于使用jQuery的$.each循环。 再来看下发表评论功能的前端代码。 $("#add").click(function(){ var user = $("#user").val(); var txt = $("#txt").val(); $.ajax({ type: "POST", url: "comment.php", data: "user="+user+"&txt="+txt, success: function(msg){ if(msg==1){ var str = ""+user+":"+txt+"刚刚
"; comments.append(str); $("#message").show().html("发表成功!").fadeOut(1000); $("#txt").attr("value",""); }else{ $("#message").show().html(msg).fadeOut(1000); } } }); }); 当输入昵称和评论内容后,点击提交,通过Ajax向后台comment.php程序发送请求,PHP对请求作出相应,并将数据插入数据库,成功后返回结果给前台。 PHP 先来看PHP读取和生成JSON数据的server.php代码。 //连接数据库 include_once("connect.php"); $q=mysql_query("select * from comments"); while($row=mysql_fetch_array($q)){ $comments[] = array("id"=>$row[id],"user"=>$row[user],"comment"=>$row[comment], "addtime"=>$row[addtime]); } echo json_encode($comments); 注意你的PHP版本应该是5.2以上才能使用json_encode函数。 再来看下发表评论的comment.php代码。 include_once("connect.php"); $user = htmlspecialchars(trim($_POST['user'])); $txt = htmlspecialchars(trim($_POST['txt'])); if(empty($user)){ echo "昵称不能为空!"; exit; } if(empty($txt)){ echo "评论内容不能为空!"; exit; } $time = date("Y-m-d H:i:s"); $query=mysql_query("insert into comments(user,comment,addtime)values('$user','$txt','$time')"); if($query) echo "1"; comment.php接收前台ajax提交过来的昵称和评论内容参数,判断参数的合法性,然后将数据插入到数据库中,如果成功,则输出1,返回给前台jQuery处理。 本例使用简单容易的代码诠释了轻量、高效的jQuery结合PHP的ajax运作机制,当然这只是一个基础的例子,jQuery还能做很多事情,留给大家去尽情发挥吧。最后,奉上数据库表结构: CREATE TABLE `comments` ( `id` int(11) NOT NULL auto_increment, `user` varchar(30) NOT NULL, `comment` varchar(200) NOT NULL, `addtime` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM; 声明:本文为原创文章,helloweba.com和作者拥有版权,如需转载,请注明来源于helloweba.com并保留原文链接,否则视为侵权。