当前位置: 移动技术网 > IT编程>开发语言>PHP > 简单的ajax评论完整代码

简单的ajax评论完整代码

2018年10月25日  | 移动技术网IT编程  | 我要评论
简单的ajax评论完整代码

 结构create table `comments` (

  `id` int(10) unsigned not null auto_increment,

  `name` varchar(128) collate utf8_unicode_ci not null default '',

  `url` varchar(255) collate utf8_unicode_ci not null default '',

  `email` varchar(255) collate utf8_unicode_ci not null default '',

  `body` text collate utf8_unicode_ci not null,

  `dt` timestamp not null default current_timestamp,

  primary key  (`id`)

) engine=myisam  default charset=utf8 collate=utf8_unicode_ci auto_increment=1;

演示

 

php code

<?php  

  

// error reporting:  

error_reporting(e_all^e_notice);  

  

include "conn.php";  

include "comment.class.php";  

  

  

/* 

/   select all the comments and populate the $comments array with objects 

*/  

  

$comments = array();  

$result = mysql_query("select * from comments order by id asc");  

  

while($row = mysql_fetch_assoc($result))  

{  

    $comments[] = new comment($row);  

}  

  

?>  

php code

<p id="main">  

  

<?php  

  

/* 

/   output the comments one by one: 

*/  

  

foreach($comments as $c){  

    echo $c->markup();  

}  

  

?>  

  

<p id="addcommentcontainer">  

    <p>add a comment</p>  

    <form id="addcommentform" method="post" action="">  

        <p>  

            <label for="name">your name</label>  

            <input type="text" name="name" id="name" />  

              

            <label for="email">your email</label>  

            <input type="text" name="email" id="email" />  

              

            <label for="url">website (not required)</label>  

            <input type="text" name="url" id="url" />  

              

            <label for="body">comment body</label>  

            <textarea name="body" id="body" cols="20" rows="5"></textarea>  

              

            <input type="submit" id="submit" value="submit" />  

        </p>  

    </form>  

</p>  

  

</p>  

 submit.php

php code

<?php  

  

// error reporting:  

error_reporting(e_all^e_notice);  

  

include "conn.php";  

include "comment.class.php";  

  

/* 

/   this array is going to be populated with either 

/   the data that was sent to the script, or the 

/   error messages. 

/*/  

  

$arr = array();  

$validates = comment::validate($arr);  

  

if($validates)  

{  

    /* everything is ok, insert to database: */  

      

    mysql_query("   insert into comments(name,url,email,body) 

                    values ( 

                        '".$arr['name']."',  

                        '".$arr['url']."',  

                        '".$arr['email']."',  

                        '".$arr['body']."'  

                    )");  

      

    $arr['dt'] = date('r',time());  

    $arr['id'] = mysql_insert_id();  

      

    /* 

    /   the data in $arr is escaped for the mysql query, 

    /   but we need the unescaped variables, so we apply, 

    /   stripslashes to all the elements in the array: 

    /*/  

      

    $arr = array_map('stripslashes',$arr);  

      

    $insertedcomment = new comment($arr);  

  

    /* outputting the markup of the just-inserted comment: */  

  

    echo json_encode(array('status'=>1,'html'=>$insertedcomment->markup()));  

  

}  

else  

{  

    /* outputtng the error messages */  

    echo '{"status":0,"errors":'.json_encode($arr).'}';  

}  

  

?>  

comment.class.php

php code

<?php  

  

class comment  

{  

    private $data = array();  

      

    public function __construct($row)  

    {  

        /* 

        /   the constructor 

        */  

          

        $this->data = $row;  

    }  

      

    public function markup()  

    {  

        /* 

        /   this method outputs the xhtml markup of the comment 

        */  

          

        // setting up an alias, so we don't have to write $this->data every time:  

        $d = &$this->data;  

          

        $link_open = ''; 

        $link_close = ''; 

         

        if($d['url']){ 

             

            // if the person has entered a url when adding a comment, 

            // define opening and closing hyperlink tags 

             

            $link_open = '<a href="'.$d['url'].'">'; 

            $link_close =  '</a>'; 

        } 

         

        // converting the time to a unix timestamp: 

        $d['dt'] = strtotime($d['dt']); 

         

        // needed for the default gravatar image: 

        $url = 'https://'.dirname($_server['server_name'].$_server["request_uri"]).'/img/default_avatar.gif';  

          

        return '  

          

            <p class="comment">  

                <p class="avatar">  

                    '.$link_open.'  

                    <img src="" />  

                    '.$link_close.'  

                </p>  

                  

                <p class="name">'.$link_open.$d['name'].$link_close.'</p>  

                <p class="date" title="added at '.date('h:i \o\n d m y',$d['dt']).'">'.date('d m y',$d['dt']).'</p>  

                <p>'.$d['body'].'</p>  

            </p>  

        '; 

    } 

     

    public static function validate(&$arr) 

    { 

        /* 

        /   this method is used to validate the data sent via ajax. 

        / 

        /   it return true/false depending on whether the data is valid, and populates 

        /   the $arr array passed as a paremter (notice the ampersand above) with 

        /   either the valid input data, or the error messages. 

        */ 

         

        $errors = array(); 

        $data   = array(); 

         

        // using the filter_input function introduced in php 5.2.0 

         

        if(!($data['email'] = filter_input(input_post,'email',filter_validate_email))) 

        { 

            $errors['email'] = 'please enter a valid email.'; 

        } 

         

        if(!($data['url'] = filter_input(input_post,'url',filter_validate_url))) 

        { 

            // if the url field was not populated with a valid url, 

            // act as if no url was entered at all: 

             

            $url = ''; 

        } 

         

        // using the filter with a custom callback function: 

         

        if(!($data['body'] = filter_input(input_post,'body',filter_callback,array('options'=>'comment::validate_text')))) 

        { 

            $errors['body'] = 'please enter a comment body.'; 

        } 

         

        if(!($data['name'] = filter_input(input_post,'name',filter_callback,array('options'=>'comment::validate_text')))) 

        { 

            $errors['name'] = 'please enter a name.'; 

        } 

         

        if(!empty($errors)){ 

             

            // if there are errors, copy the $errors array to $arr: 

             

            $arr = $errors; 

            return false; 

        } 

         

        // if the data is valid, sanitize all the data and copy it to $arr: 

         

        foreach($data as $k=>$v){ 

            $arr[$k] = mysql_real_escape_string($v); 

        } 

         

        // ensure that the email is lower case: 

         

        $arr['email'] = strtolower(trim($arr['email'])); 

         

        return true; 

         

    } 

 

    private static function validate_text($str) 

    { 

        /* 

        /   this method is used internally as a filter_callback 

        */ 

         

        if(mb_strlen($str,'utf8')<1) 

            return false; 

         

        // encode all html special characters (<, >, ", & .. etc) and convert 

        // the new line characters to <br> tags: 

         

        $str = nl2br(htmlspecialchars($str)); 

         

        // remove the new line characters that are left 

        $str = str_replace(array(chr(10),chr(13)),'',$str);  

          

        return $str;  

    }  

  

}  

  

?>  

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网