简单的ajax评论完整代码

前端之家收集整理的这篇文章主要介绍了简单的ajax评论完整代码前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

简单的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
  1. <?PHP
  2. //Errorreporting:
  3. error_reporting(E_ALL^E_NOTICE);
  4. include"conn.PHP";
  5. include"comment.class.PHP";
  6. /*
  7. /Selectallthecommentsandpopulatethe$commentsarraywithobjects
  8. */
  9. $comments=array();
  10. $result=MysqL_query("SELECT*FROMcommentsORDERBYidASC");
  11. while($row=MysqL_fetch_assoc($result))
  12. {
  13. $comments[]=newComment($row);
  14. }
  15. ?>
<divid="main">
  • /*
  • /Outputthecommentsonebyone:
  • */
  • foreach($commentsas$c){
  • echo$c->markup();
  • }
  • ?>
  • <divid="addCommentContainer">
  • <p>AddaComment</p>
  • <formid="addCommentForm"method="post"action="">
  • <div>
  • <labelfor="name">YourName</label>
  • <inputtype="text"name="name"id="name"/>
  • <labelfor="email">YourEmail</label>
  • <inputtype="text"name="email"id="email"/>
  • <labelfor="url">Website(notrequired)</label>
  • <inputtype="text"name="url"id="url"/>
  • <labelfor="body">CommentBody</label>
  • <textareaname="body"id="body"cols="20"rows="5"></textarea>
  • <inputtype="submit"id="submit"value="Submit"/>
  • </div>
  • </form>
  • </div>
  • submit.PHP

    /Thisarrayisgoingtobepopulatedwitheither
  • /thedatathatwassenttothescript,orthe
  • /errormessages.
  • /*/
  • $arr=array();
  • $validates=Comment::validate($arr);
  • if($validates)
  • {
  • /*EverythingisOK,inserttodatabase:*/
  • MysqL_query("INSERTINTOcomments(name,url,email,body)
  • VALUES(
  • '".$arr['name']."',
  • '".$arr['url']."',
  • '".$arr['email']."',0);">'".$arr['body']."'
  • )");
  • $arr['dt']=date('r',time());
  • $arr['id']=MysqL_insert_id();
  • /Thedatain$arrisescapedfortheMysqLquery,0);">/butweneedtheunescapedvariables,soweapply,0);">/stripslashestoalltheelementsinthearray:
  • $arr=array_map('stripslashes',$arr);
  • $insertedComment=newComment(/*Outputtingthemarkupofthejust-insertedcomment:*/
  • echojson_encode(array('status'=>1,'html'=>$insertedComment->markup()));
  • else
  • /*Outputtngtheerrormessages*/
  • echo'{"status":0,"errors":'.json_encode($arr).'}';
  • ?>
  • comment.class.PHP

    classComment
  • private$data=array();
  • publicfunction__construct($row)
  • /Theconstructor
  • $this->data=$row;
  • publicfunctionmarkup()
  • /ThismethodoutputstheXHTMLmarkupofthecomment
  • //Settingupanalias,sowedon'thavetowrite$this->dataeverytime:
  • $d=&$this->data;
  • $link_open='';
  • $link_close='';
  • if($d['url']){
  • //IfthepersonhasenteredaURLwhenaddingacomment,0);">//defineopeningandclosinghyperlinktags
  • $link_open='<ahref="'.$d['url'].'">';
  • $link_close='</a>';
  • }
  • //ConvertingthetimetoaUNIXtimestamp:
  • $d['dt']=strtotime($d['dt']);
  • //Neededforthedefaultgravatarimage:
  • $url='http://'.dirname($_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"]).'/img/default_avatar.gif';
  • return'
  • <divclass="comment">
  • <divclass="avatar">
  • '.$link_open.'
  • <imgsrc=""/>
  • '.$link_close.'
  • <divclass="name">'.$link_open.$d['name'].$link_close.'</div>
  • <divclass="date"title="Addedat'.date('H:i\o\ndMY',$d['dt']).'">'.date('dMY',$d['dt']).'</div>
  • <p>'.$d['body'].'</p>
  • </div>
  • ';
  • publicstaticfunctionvalidate(&$arr)
  • {
  • /*
  • /ThismethodisusedtovalidatethedatasentviaAJAX.
  • /
  • /Itreturntrue/falsedependingonwhetherthedataisvalid,andpopulates
  • /the$arrarraypassedasaparemter(noticetheampersandabove)with
  • /eitherthevalidinputdata,ortheerrormessages.
  • */
  • $errors=array();
  • $data=array();
  • //Usingthefilter_inputfunctionintroducedinPHP5.2.0
  • if(!($data['email']=filter_input(INPUT_POST,'email',FILTER_VALIDATE_EMAIL)))
  • {
  • $errors['email']='PleaseenteravalidEmail.';
  • if(!($data['url']=filter_input(INPUT_POST,'url',FILTER_VALIDATE_URL)))
  • //IftheURLfieldwasnotpopulatedwithavalidURL,0);">//actasifnoURLwasenteredatall:
  • $url='';
  • //Usingthefilterwithacustomcallbackfunction:
  • if(!($data['body']=filter_input(INPUT_POST,'body',FILTER_CALLBACK,array('options'=>'Comment::validate_text'))))
  • $errors['body']='Pleaseenteracommentbody.';
  • }
  • if(!($data['name']=filter_input(INPUT_POST,'name',array('options'=>'Comment::validate_text'))))
  • $errors['name']='Pleaseenteraname.';
  • if(!empty($errors)){
  • //Ifthereareerrors,copythe$errorsarrayto$arr:
  • $arr=$errors;
  • returnfalse;
  • //Ifthedataisvalid,sanitizeallthedataandcopyitto$arr:
  • foreach($dataas$k=>$v){
  • $arr[$k]=MysqL_real_escape_string($v);
  • //Ensurethattheemailislowercase:
  • $arr['email']=strtolower(trim($arr['email']));
  • returntrue;
  • privatestaticfunctionvalidate_text($str)
  • /ThismethodisusedinternallyasaFILTER_CALLBACK
  • if(mb_strlen($str,'utf8')<1)
  • //Encodeallhtmlspecialcharacters(<,>,",&..etc)andconvert
  • //thenewlinecharactersto<br>tags:
  • $str=nl2br(htmlspecialchars($str));
  • //Removethenewlinecharactersthatareleft
  • $str=str_replace(array(chr(10),chr(13)),'',0);">$str);
  • return$str;

  • 原文地址:http://www.freejs.net/article_biaodan_70.html

    原文链接:https://www.f2er.com/ajax/165674.html
  • 猜你在找的Ajax相关文章