Smarty结合Ajax实现无刷新留言本实例

看了标题你也许要说,留言本,很基本的东东啊!谁不会啊,还要用Smarty,这不找累吗?别急,我要表达的是一种编程的思想和结构,而不是证明我做的东西多有意义,通过它相信对初学者学习Smarty和ajax有些启发。原本用ajax做的,可惜始终调试不成功,只好用手写JS来弄了,不过不要紧,还是有一定价值的。站点结构大家下了源代码自己看,代码不长,应该不会看烦^_^,听我慢慢道来。
     现在都PHP5了OO(面向对象)很流行了都,这里也不错过,首先来看下我们用OO来实现数据库操作和连接:
[php]
<?php
/**************************

页面:dbclass.php
  作者:辉老大
  功能:定义数据库操作类
**************************/
<?php
/**************************

页面:dbclass.php
  作者:辉老大
  功能:定义数据库操作类
**************************/
class db{
       //创建构造函数,作用:数据库连接并选择相应数据库
       public function __construct(){
     require('config.inc.php');
           mysql_connect($dbhost,$dbuser,$dbpassword) or die("error!");
     mysql_query("SET NAMES 'GBK'");
           mysql_select_db($dbname);
       }
    //执行SQL语句函数
    public function query($sql){
        return mysql_query($sql);
    }
    //取得结果集数组函数
    public function loop_query($result){
        return mysql_fetch_array($result);
    }
    //创建析构函数,作用:关闭数据库连接
    public function __destruct(){
     return mysql_close();
    }
   }
?> 
这个类有什么特点呢?首先介绍下__construct()是构造函数,啥是构造函数?通俗点讲就是类被实例化后就自动执行的函数,__destruct()是啥?是析构函数,它的作用就是在没有任何方法指向这个对象时,便自动销毁对象,里面一般包含一些收尾的操作,比如关闭文件,关闭数据库连接之类的方法,看到这你是不是明白一些了?没错!在类实例化的时候自动执行带有数据库连接方法的构造函数,在实例销毁的时候执行关闭数据库连接的析构函数,对于一些基本数据操作我们只要new一个$db对象,然后$db->query()...是不是很方便,当然,这只是一个简单的例子,你还可以继续扩展。来看看 config.inc.php里面是什么:
很容易对不对,感兴趣就接着看吧^_^,来看下模板文件:

<?php
/*************************

页面:config.inc.php
   作者:辉老大
   功能:数据库参数变量设定
   $dbhost:主机名
   $dbuser:连接帐户
   $dbpassword:连接密码
   $dbname:数据库名
*************************/
   $dbhost     = "localhost";
   $dbuser     = "root";
   $dbpassword = "7529639";
   $dbname     = "testdb";
?>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk" />
<title><{$title}></title>
<style type="text/css">
<!--
.username {
height: 20px;
width: 250px;
}
.comment {
height: 100px;
width: 660px;
}
body,td,tr {
font-size: 9pt;
}
-->
</style>
<script language="javascript" src="./inc/ajax.js"></script>
</head>
<body>
<div align="right" id="check"></div>
<div id="result"><{*这里显示留言内容*}>
<{section name=loop loop=$bookinfo}><{*循环显示留言*}>
用户名:<{$bookinfo[loop].username}> 内容:<{$bookinfo[loop].comment}><p>
<{/section}>
</div>
<form method="post" name="book" id="book">
  <table width="760" border="1" cellpadding="0" cellspacing="0">
    <tr>
      <td width="80" height="30" align="center">用户名:</td>
      <td height="30"> <input name="username" type="text" class="username" id="username"></td>
    </tr>
    <tr>
      <td width="80" height="120" align="center">留言内容:</td>
      <td height="120"> <textarea name="comment" class="comment" id="comment"></textarea></td>
    </tr>
  </table>
  <input type="button" name="button" value="发布" onClick="send('result');">
  </form>
</body>
</html>

模板中的内容在<{}>中的一会会被PHP替换掉,这就实现了美工和程序员的分工,不错吧有关Smarty的内容还请参考手册,这里就不便多说。来看下页面是怎么输出模板的吧:

<?php
  /*****************************************
   Title :Smarty结合Ajax留言板实例
   Author:leehui1983(辉老大)
   Page Name:index.php
   Finish Date  :2006-12-17
  *****************************************/

require('./libs/Smarty.class.php');//包含smarty类库
  require('./inc/dbclass.php');//包含数据库操作类

$db = new db();//生成数据库操作实例
  $smarty = new Smarty();//实例化smarty对象
  $smarty->template_dir = "./templates";//设置模板目录
  $smarty->compile_dir  = "./templates_c"; //设置编译目录
  $smarty->caching      = false; //设置缓存方式
  /*****************************************************
  左右边界符,默认为{},但实际应用当中容易与JavaScript
  相冲突,所以建议设成<{}>或其它。
  *****************************************************/
  $smarty->left_delimiter  = "<{"; 
  $smarty->right_delimiter = "}>";
  $smarty->assign('title','smarty结合ajax制作简单留言板');//替换模板内容
  //设置初始页面由Smarty显示的留言内容
  $rt=$db->query("select * from bookinfo order by id desc");
  while($rs=$db->loop_query($rt)){
   $array[]=array("username"=>$rs['username'],"comment"=>$rs['comment']);
  }
  $smarty->assign("bookinfo",$array);
  unset ($array);//销毁数组变量
  $smarty->display("index.tpl");//编译并显示位于./templates下的index.tpl模板
?> 
页面实例的注释还是比较多的,大家参考下Smarty手册这个是So easy的!!呵呵~~~~
接下来到了介绍ajax的时候,这里我们用一个基本的开发框架来实现,关于ajax的知识建议大家看看网上非常流行的电子教程ajax开发简略
var http_request=false;
  function send_request(url){//初始化,指定处理函数,发送请求的函数
    http_request=false;
//开始初始化XMLHttpRequest对象
if(window.XMLHttpRequest){//Mozilla浏览器
  http_request=new XMLHttpRequest();
  if(http_request.overrideMimeType){//设置MIME类别
    http_request.overrideMimeType("text/xml");
  }
}
else if(window.ActiveXObject){//IE浏览器
  try{
   http_request=new ActiveXObject("Msxml2.XMLHttp");
  }catch(e){
   try{
   http_request=new ActiveXobject("Microsoft.XMLHttp");
   }catch(e){}
  }
    }
if(!http_request){//异常,创建对象实例失败
  window.alert("创建XMLHttp对象失败!");
  return false;
}
http_request.onreadystatechange=processrequest;
//确定发送请求方式,URL,及是否同步执行下段代码
    http_request.open("GET",url,true);
http_request.send(null);
  }
  //处理返回信息的函数
  function processrequest(){
   if(http_request.readyState==4){//判断对象状态
     if(http_request.status==200){//信息已成功返回,开始处理信息
   document.getElementById(reobj).innerHTML=http_request.responseText;
  }
  else{//页面不正常
   alert("您所请求的页面不正常!");
  }
   }
  }
  function send(obj){
   var f=document.book;
   var username=f.username.value;
   var comment=f.comment.value;
   if(username==""||comment==""){
   document.getElementById(obj).innerHTML="<font color=red>请填写完整!</font>";
   return false;
   }
   else{
   send_request('checkbookinfo.php?username='+username+'&comment='+comment);
   reobj=obj;
   }
  }

这样我们点“发布”按钮,数据就会交由服务器异步处理,通过JS来组织异步更新,在发过留言后你马上就能看见你的留言而不是传统的等待页面跳转,那么数据传到哪里处理呢?看这里:
<?php

/*****************************************
   Title :Smarty结合Ajax留言板实例
   Author:leehui1983(辉老大)
   Page Name:checkbookinfo.php
   Finish Date  :2006-12-17
  *****************************************/
  header("Content-type: text/html;charset=GBK");//输出编码,避免中文乱码
  include('./inc/dbclass.php');//包含数据库操作类
  $db=new db();//生成数据库操作实例
  $sql="insert into bookinfo values(0,'".$comment."','".$username."')";
  $db->query($sql);
  $querysql="select * from bookinfo order by id desc";
  $result=$db->query($querysql);
  while($rows=$db->loop_query($result)){//打印留言列表,用于实时更新
  //$arr.="用户名:{$rows['username']} 内容:{$rows['comment']}<p>";
  echo '用户名:'.$rows['username'].' 内容:'.$rows['comment'].'<p>';
  }
  //echo $arr;

?>

嗯,先插入数据,在将更新后的数据通过JS组织显示,AJAX看来真的不错哦!大体就介绍完了,不知道大家想过没有,加个 iframe可以改成什么?对!无刷新聊天室,发挥你的能力,实现一个看看。这个例子用到了OO,AJAX,SMARTY,东西还是蛮多滴,希望大家喜欢,我已经决定将此文向PHP杂志投稿,大家若是转载,还希望注明版权,谢谢!最后来个效果图~~~~

(0)

相关推荐

  • smarty半小时快速上手入门教程

    本文讲述了smarty快速上手入门的方法,可以让读者在半小时内快速掌握smarty的用法.分享给大家供大家参考.具体实现方法如下: 一.smarty的程序设计部分: 在smarty的模板设计部分我简单的把smarty在模板中的一些常用设置做了简单的介绍,这一节主要来介绍一下如何在smarty中开始我们程序设计.下载Smarty文件放到你们站点中. index.php代码如下: 复制代码 代码如下: <?php /** * * @version $Id: index.php * @package

  • Smarty Foreach 使用说明

    foreach 是除 section 之外处理循环的另一种方案(根据不同需要选择不同的方案). foreach 用于处理简单数组(数组中的元素的类型一致),它的格式比 section 简单许多,缺点是只能处理简单数组. foreach 必须和 /foreach 成对使用,且必须指定 from 和 item 属性. 将 from 属性指定的数组中的数据遍历处理到 item 属性指定的变量中. 参考 foreach (array_expression as $key => $value) from

  • php Smarty date_format [格式化时间日期]

    Example 5-8. date_format[日期格式] index.php: 复制代码 代码如下: $smarty = new Smarty; $smarty->assign('yesterday', strtotime('-1 day')); $smarty->display('index.tpl'); index.tpl: {$smarty.now|date_format} {$smarty.now|date_format:"%A, %B %e, %Y"} {$s

  • 使用Smarty 获取当前日期时间和格式化日期时间的方法详解

    在Smarty 中获取当前日期时间和格式化日期时间与PHP中有些不同的地方,这里就为您详细介绍: 首先是获取当前的日期时间:在PHP中我们会使用date函数来获取当前的时间,实例代码如下:date("Y-m-dH:i:s");   //该结果会显示为:2010-07-27 21:19:36 的模式 但是在Smarty 模板中我们就不能使用date 了,而是应该使用 now 来获取当前的时间,实例代码如下:{$smarty.now}      //该结果会显示为:1280236776的时

  • PHP详细彻底学习Smarty

    基本语法  所有的smarty标签都被加上了定界符.在smarty里,所有定界符以外的内容都是静态的,当smarty遇到了模板标签,将尝试解释他们,然后再以恰当的方式输出. 默认情况下是 {和},但它们是可定制的.定制方法是:  $smarty->left_delimiter = '<!--{';  $smarty->right_delimiter = '}-->'; 1.注释 模板注释被*号包围,例如 {* this is a comment *}  smarty注释将不被输出.

  • 解决css和js的{}与smarty定界符冲突问题的两种方法

    当输入url地址后网页出现:Fatal error: Uncaught exception 'SmartyCompilerException' with message 'Syntax Error in template "E:\wamp\www\cms\system/templates/index.html" on line 79 "$("#job").load("./system/templates/touch/test.php",

  • 在smarty模板中使用PHP函数的方法

    sample1 复制代码 代码如下: <{$colname|trim}> 那如果使用像iconv这样的有三个参数的函数该怎么写呢?如果写成: sample 2 复制代码 代码如下: <{$colname|iconv:'utf-8':'gbk'}> 一执行就会发现显示error信息. 因此研究一下就会发现,起始在smarty模板页的套用函数用法中,以smaple 1来说,trim的前面$Row->colname其实就是trim的第一个参数,中间用|这个符号串接: 那假设要使用像

  • ThinkPHP使用smarty模板引擎的方法

    ThinkPHP支持多种php模板引擎,可以根据个人需要加以配置. 下面我们以Smarty模板引擎为例,给大家说说具体的操作流程! 首先去Smarty官网上下载一个Smarty.本站下载地址:http://www.jb51.net/codes/16086.html. 接下来解压压缩包,会有两个文件夹:demo和libs.打开libs文件夹,复制所有内容. 接下来,打开你网站根目录 下thinkphp的文件夹.里面有个vendor文件夹,这个文件夹是TP调用第三方类库用的,把刚才复制的东西全部粘贴

  • smarty内部日期函数html_select_date()用法实例分析

    本文实例讲述了smarty内部日期函数html_select_date()的用法.分享给大家供大家参考.具体如下: 主要属性: prefix         //string类型 默认前缀名为"Date_" start_year     //string类型 默认为当前年份 仍可以用(+/-N)模式表示 如start_year="-10" option就从1998年开始 end_year     //string类型 默认同上 可用(+/-N)模式表示 如end_y

  • 在smarty中调用php内置函数的方法

    相信有很多朋友还不知道,可以在smarty模板里调用php的内置函数,我们一起来看看它的用法. 模板书写: {'param1'|functionName:'param2':'param3'} php函数原型: echo functionName('param1','param2','param3'); 实例: {'1234567'|substr:'1':'2'} 下面这个和函数的参数顺序有关系 {'a'|str_replace:'A':'abcd'} 直接延伸到,直接在php中写一个函数调用,不

  • Smarty日期时间操作方法示例

    本文实例讲述了Smarty日期时间操作方法.分享给大家供大家参考,具体如下: $smarty = new Smarty; $smarty->assign('yesterday', strtotime('-1 day')); $smarty->display('index.tpl'); index.tpl: {$smarty.now|date_format} //Sep 7, 2009 {$smarty.now|date_format:"%A, %B %e, %Y"} {$s

  • 解析smarty模板中类似for的功能实现

    1. 功能说明,在页面使用smarty循环100次输出,类似for循环100次{section name=total loop=100}{$smarty.section.total.index+1} //当前的索引{$smarty.section.total.iteration} //用于显示循环的次数{/section} {assign var=i value=0}{section name=total loop=100}{assign var=i value=$i+1} {$i}     /

随机推荐