jQuery+PHP+MySQL发表评论,无刷新评论完整代码
JavaScript Code
- <script type="text/javascript">
- $(function() {
- var comments = $("#comments");
- $.getJSON("ajax.php", function(json) {
- $.each(json, function(index, array) {
- var txt = "<p><strong>" + array["user"] + "</strong>:" + array["comment"] + "<span>" + array["addtime"] + "</span></p>";
- comments.append(txt);
- });
- });
- $("#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 = "<p><strong>" + user + "</strong>:" + txt + "<span>刚刚</span></p>";
- comments.prepend(str);
- $("#message").show().html("发表成功!").fadeOut(1000);
- $("#txt").attr("value", "");
- } else {
- $("#message").show().html(msg).fadeOut(1000);
- }
- }
- });
- });
- });
- </script>
XML/HTML Code
- <div class="demo">
- <div id="post">
- <h3>发表评论</h3>
- <p>昵称:</p>
- <p><input type="text" class="input" id="user" /></p>
- <p>评论内容:</p>
- <p><textarea class="input" id="txt" style="width:100%; height:80px"></textarea></p>
- <p><input type="submit" class='btn'value="发表" id="add" /></p>
- <div id="message"></div>
- </div>
- <div id="comments"></div>
- </div>
ajax.php
PHP Code
- require('conn.php');
- $q=mysql_query("select * from comments order by id desc");
- while($row=mysql_fetch_array($q)){
- $comments[] = array("id"=>$row['id'],"user"=>$row['name'],"comment"=>$row['body'],"addtime"=>$row['dt']);
- }
- echo json_encode($comments);
comment.php
PHP Code
- $user = htmlspecialchars(trim($_POST['user']));
- $txt = htmlspecialchars(trim($_POST['txt']));
- if(emptyempty($user)){
- echo "昵称不能为空";
- exit;
- }
- if(emptyempty($txt)){
- echo "评论内容不能为空";
- exit;
- }
- $time = date("Y-m-d H:i:s");
- $query=mysql_query("insert into comments(name,body,dt)values('$user','$txt','$time')");
- if($query) echo "1";
原文地址:http://www.freejs.net/article_biaodan_552.html