\n'); } function setFlash(){ var myFlshObj = document.myFlash; var photoAlbum=document.getElementById('photoAlbum'); if(photoAlbum&&myFlshObj){ var awidth=0; awidth=parseInt(photoAlbum.offsetWidth); if(awidth<260) myFlshObj.height='150px'; if(awidth>=260 && awidth<350) myFlshObj.height='240px'; if(awidth>=350 && awidth<370) myFlshObj.height='305px'; if(awidth>=370 && awidth<550) myFlshObj.height='320px'; if(awidth>=550 && awidth<730) myFlshObj.height='455px'; if(awidth>=730) myFlshObj.height='590px'; } } function setAlbumUrl(name){ albumTypename=name; setFlash(); myFlash_DoFSCommand(null,"test"); } function showLoginWindow(ev){ var obj = document.getElementById("pop-login"); if(document.all){ obj.style.top = ev.clientY +'px'; obj.style.left = ev.clientX - 272 +'px'; } else{ obj.style.top = ev.pageY +'px'; obj.style.left = ev.pageX - 272 +'px' } obj.style.display ="block"; document.getElementById("pop-user-name").focus(); } function hideLoginWindow(){ document.getElementById("pop-login").style.display ="none"; } var blogID=getBlogID(); var UserName = ""; if(blogID!=null){ var tmpUserName=blogID.split("."); UserName=tmpUserName[0]; } function resize(obj){ if(window.event.srcElement.tagName == 'A'){ return; } obj.parentNode.childNodes[1].style.display = obj.parentNode.childNodes[1].style.display=='none' ? 'block': 'none'; obj.parentNode.childNodes[2].style.display = obj.parentNode.childNodes[2].style.display=='none' ? 'block': 'none'; } function tab(event){ var evt = (document.all)?window.event:event; if(evt.keyCode == 9){ document.getElementById("pop-password").focus(); return false; } else{ return evt.keyCode; } } function tab1(event){ var evt = (document.all)?window.event:event; if(evt.keyCode == 9){ document.getElementById("save").focus(); return false; } else{ return evt.keyCode; } } function tabTrack(event) { var evt = (document.all)?window.event:event; if(evt.keyCode == 9){ document.getElementById("pop-password-track").focus(); return false; } else{ return evt.keyCode; } }
PHP,Ajax,Smarty...
日志
<?php
/*
*页面:makeJs.class.php
*功能:封装常用的JS代码,直接调用,方便操作
*作者:辉老大
*创建时间:2007-01-27
*/
class makeJs
{
private $jsStartChar = '<script type="text/javascript">';//定义js起始标记
private $jsEndChar = '</script>';//定义js结束标记
/*
*函数名称:jsAlert
*函数功能:弹出JS提示框
*参数:$message 要在弹出提示框中显示的文字 $url 点击后跳转的路径,为空则不跳转
*使用方法:
*$js = new makeJs();//以下介绍使用方法省略此句
*$js->jsAlert(显示的文字,'跳转页面URL');//弹出对话框,点击确定后跳转到php.php页面
*$js->jsAlert(显示的文字,'');//弹出对话框,点击确定后没有跳转
*/
public function jsAlert($message,$url){
echo $this->jsStartChar;
if($url==''){
echo 'alert' . '("' . $message . '");';
echo $this->jsEndChar;
}
else{
echo 'alert' . '("' . $message . '");';
echo $this->jsEndChar;
echo '<meta http-equiv="refresh" c>';
}
}
/*
*函数名称:jsConfirm
*函数功能:弹出JS提示框,带确定/取消
*参数:$message 要在弹出提示框中显示的文字
*使用方法:$js->jsConfirm('显示的文字');
*/
public function jsConfirm($message){
echo $this->jsStartChar;
if($url==''){
echo 'confirm' . '("' . $message . '");';
echo $this->jsEndChar;
}
}
/*
*函数名称:jsOpenWin
*函数功能:弹出新窗口
*参数:$url 路径 $name 窗口名 $height 窗口高度 $width 窗口宽度
*使用方法:
*$url = '页面的URL';
*$js->jsOpenWin($url,窗口名,窗口高度,窗口宽度);
*/
public function jsOpenWin($url,$name,$height,$width){
echo $this->jsStartChar;
echo 'window.open'.'("'.$url.'","'.$name.'","'.$height.'","'.$width.'");';
echo $this->jsEndChar;
}
/*
*函数名称:jsAddScript
*函数功能:自定义JS
*参数:$script
*使用方法:
*$script = '定义的js语句';
*例如:$script = 'window.location=('php.php')';
*$js->jsAddScript($script);
*/
public function jsAddScript($script){
echo $this->jsStartChar;
echo $script;
echo $this->jsEndChar;
}
}
?>
<?php
/*
*作者:辉老大
*页面:path.cfg.php
*功能:系统路径设置
*版权所有:随便copy^_^
*/
$global['path']['conf'] = $global['path']['root'] . 'conf/';//定义系统配置文件路径
$global['path']['lib'] = $global['path']['root'] . 'lib/';//定义系统库文件路径
?>
<?php
/*
*作者:辉老大
*页面:smarty.cfg.php
*功能:smarty基本配置
*版权所有:随便copy^_^
*/
//定义模板路径
$global['smarty']['template_dir'] = $global['path']['root'] . 'lib/smarty/templates';
//定义模板编译目录
$global['smarty']['compile_dir'] = $global['path']['root'] . 'lib/smarty/templates_c';
//定义smarty配置文件夹路径
$global['smarty']['config_dir'] = $global['path']['conf'] . 'lib/smarty/configs';
$global['smarty']['cache_dir'] = $global['path']['root'] . 'lib/smarty/cache';
//$global['smarty']['compile_check'] = true;
//设置smarty报错禁用
$global['smarty']['debugging'] = false;
//关闭缓存
$global['smarty']['caching'] = false;
//$global['smarty']['cache_lifetime'] = 6000;
//定义左右边界符
$global['smarty']['left_delimiter'] = '<{';
$global['smarty']['right_delimiter'] = '}>';
?>
<?php
/*
*作者:辉老大
*页面:common.cfg.php
*功能:全局配置
*版权所有:随便copy^_^
*/
$global['path']['root'] = dirname(__FILE__) . '/';//设置根目录
require($global['path']['conf'] . 'conf/path.cfg.php');
require($global['path']['conf'] . 'smarty.cfg.php');
//包含smarty类库
require($global['path']['lib'] . 'smarty/libs/Smarty.class.php');
//smarty配置
$tpl = new Smarty();
$tpl->template_dir = $global['smarty']['template_dir'];
$tpl->compile_dir = $global['smarty']['compile_dir'];
$tpl->config_dir = $global['smarty']['config_dir'];
$tpl->debugging = $global['smarty']['debugging'];
$tpl->caching = $global['smarty']['caching'];
$tpl->cache_lifetime = $global['smarty']['cache_lifetime'];
$tpl->left_delimiter = $global['smarty']['left_delimiter'];
$tpl->right_delimiter = $global['smarty']['right_delimiter'];
unset($global['smarty']);
ini_set('include_path', ini_get('include_path') .
PATH_SEPARATOR . $global['path']['lib'] . 'pear/');//载入pear库文件
?>
<?php
/*
*作者:辉老大
*页面:index.php
*功能:UI
*版权所有:随便copy^_^
*/
require_once('common.inc.php');//载入全局配置
//包含quickform类库
require($global['path']['lib'] . 'pear/HTML/QuickForm.php');
$form = new HTML_QuickForm('changepwdform');//生成quickform实例,参数为表单名
/*
*开始添加表单元素
*参数依次为:表单元素类型,名称,(按钮标签文字),样式
*/
$form->addElement('password','adminPwd','','style="width:120px"');
$form->addElement('password','newPwd','','style="width:120px"');
$form->addElement('password','newPwd2','','style="width:120px"');
$form->addElement('submit','btnSubmit','修改密码','style="width:100px"');
//增加验证规则,自动生成JS
$form->addRule('adminPwd','密码不能为空!','required','','client');
$form->addRule('newPwd','新密码不能为空!','required','','client');
$form->addRule('newPwd2','请再次输入新密码!','required','client');
$form->addRule(array('newPwd','newPwd2'),"两次输入的密码不一致!",'compare','','client');
$form->;//禁止提交表单
//分配表单数据到数组中
$tpl->assign('form_data',$form->toArray());
//显示模板
$tpl->display('index.tpl');
?>
$form->addRule(array('newPwd','newPwd2'),"两次输入的密码不一致!",'compare','','client');
<?php
/**************************************
页面:menu.php
作者:辉老大
功能:定义数据库操作及生成菜单列表类
**************************************/
class menu{
//创建构造函数,作用:数据库连接并选择相应数据库
public function __construct(){
$dbhost = "localhost";
$dbuser = "root";
$dbpassword = "7529639";
$dbname = "menu";
mysql_connect($dbhost,$dbuser,$dbpassword) or die("error!");
mysql_query("SET NAMES 'GBK'");
mysql_select_db($dbname);
}
//执行SQL语句函数
private function query($sql){
return mysql_query($sql);
}
//取得结果集数组函数
private function loop_query($result){
return mysql_fetch_array($result);
}
//列出菜单列表函数
public function menulist(){
$sql="select * from list order by path";
$result=$this->query($sql);
while($rows=$this->loop_query($result)){
if(substr_count($rows['path'],',')>2){
for($i=0;$i<(substr_count($rows['path'],',')-2);$i++)
echo ' ';
}
echo $rows['name'].'<br>';
}
}
//创建析构函数,作用:关闭数据库连接
public function __destruct(){
return mysql_close();
}
}
$db=new menu();//生成实例
$db->menulist();//调用方法生成菜单
?>

<html>
<head>
<meta http-equiv="Content-Type" c />
<title>类别目录树</title>
<script type="text/javascript">
function ShowMenu(MenuID)
{
if(MenuID.style.display=="none"){
MenuID.style.display="";
}
else{
MenuID.style.display="none";
}
}
</script>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body topmargin="0" bgcolor="#EFEFE7">
<table width="100%" height="25" border="0" cellpadding="0" cellspacing="0" bgcolor="#739E18">
<tr>
<td align="left"> <strong>栏目树形结构列表</strong></td>
</tr>
</table>
<?php
//基本变量设置
$GLOBALS["ID"] =1; //用来跟踪下拉菜单的ID号
$layer=1; //用来跟踪当前菜单的级数
//连接数据库
$Con=mysql_connect("localhost","root","7529639");
mysql_select_db("cr_download");
mysql_query("SET NAMES 'GBK'");
//提取一级菜单
$sql="select * from cr_columninfo where columnfatherid=0";
$result=mysql_query($sql,$Con);
//如果一级菜单存在则开始菜单的显示
if(mysql_num_rows($result)>0) ShowTreeMenu($Con,$result,$ID);
//=============================================
//显示树型菜单函数 ShowTreeMenu($con,$result,$layer)
//$con:数据库连接
//$result:需要显示的菜单记录集
//$layer:需要显示的菜单的级数
//=============================================
function ShowTreeMenu($Con,$result,$layer)
{
//取得需要显示的菜单的项目数
$numrows=mysql_num_rows($result);
//开始显示菜单,每个子菜单都用一个表格来表示
echo "<table cellpadding='0' cellspacing='0' border='0' width='100%'>";
for($rows=0;$rows<$numrows;$rows++)
{
//将当前菜单项目的内容导入数组
$menu=mysql_fetch_array($result);
//提取菜单项目的子菜单记录集
$sql="select * from cr_columninfo where columnfatherid=$menu[columnid]";
$result_sub=mysql_query($sql,$Con);
echo "<tr>";
//如果该菜单项目有子菜单,则添加JavaScript onClick语句
if(mysql_num_rows($result_sub)>0)
{
echo "<td width='20'><img src='./images/plus.png' border='0' > </td>";
echo "<td class='Menu' >";
}
else{
echo "<td width='20'><img src='./images/page.png' border='0'> </td>";
echo "<td class='Menu'>";
}
//如果该菜单项目没有子菜单,只显示菜单名称
echo $menu[columnname];
echo "</td></tr>";
//如果该菜单项目有子菜单,则显示子菜单
if(mysql_num_rows($result_sub)>0)
{
//指定该子菜单的ID和style,以便和onClick语句相对应
echo "<tr id=Menu".$GLOBALS["ID"]++." style='display:none'>";
echo "<td width='20'> </td>";
echo "<td>";
//将级数加1
$layer++;
//递归调用ShowTreeMenu()函数,生成子菜单
ShowTreeMenu($Con,$result_sub,$layer);
//子菜单处理完成,返回到递归的上一层
echo "</td></tr>";
}
//子菜单处理完成,返回到递归的上一层,将级数减1
$layer--;
}
echo "</table>";
}
?>
</body>
</html>
<?php
include('global.php');
include('../inc/config.inc.php');
include('../inc/dbclass.php');
$a=strtolower(fileext($_FILES['file']['name']));
//判断文件类型
if(!in_array(strtolower(fileext($_FILES['file']['name'])),$type))
{
$text=implode(",",$type);
echo "您只能上传以下类型文件: ",$text,"<br>";
}
//生成目标文件的文件名
else{
$filename=explode(".",$_FILES['file']['name']);
do
{
$filename[0]=random(10); //设置随机数长度
$name=implode(".",$filename);
//$name1=$name.".Mcncc";
$uploadfile=$uploaddir.$name;
}
while(file_exists($uploadfile));
if (move_uploaded_file($_FILES['file']['tmp_name'],$uploadfile)){
$db=new db;//创建数据库连接对象
$db->mysql($dbhost,$dbuser,$dbpassword,$dbname);//调用连接参数函数
$db->createcon();//调用创建连接函数
$time=date("Y-m-d");
$url=$patch.$name;
$upsql="insert into cr_uploadfile values (0,'$name','$url','$uploadfile','$time',0)";
if($db->query($upsql)){
//输出图片预览
echo "<center>您的文件已经上传完毕 上传图片预览: </center><br><center><img src='$uploadfile'></center>";
echo"< br><center><a href='history.go(-1)'>继续上传< /a> <a href=../admin/upfileman.php>管理</a></center>";
}
else{
echo "上传失败!";
}
}
}
$db->close();//关闭数据库连接
?>
<?php
include('../inc/config.inc.php');
include('../inc/dbclass.php');
include('../inc/pageft.php');
$db=new db;//从数据库操作类生成实例
$db->mysql($dbhost,$dbuser,$dbpassword,$dbname);//调用连接参数函数
$db->createcon();//调用创建连接函数
?>
<script type="text/javascript">
function ConfirmDel()
{
if(confirm("确认删除?并且不能恢复!确定要删除该文件吗?"))
return true;
else
return false;
}
</script>
<html>
<head>
<meta http-equiv="Content-Type" c />
<title>上传文件管理</title>
<style type="text/css">
<!--
body,td,th {
font-size: 9pt;
}
body {
background-color: #EFEFE7;
}
.s1 {
font-weight: bold;
color: #FFFFFF;
}
a:link {
color: #0000FF;
text-decoration: none;
}
a:visited {
color: #0000FF;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
a:active {
text-decoration: underline;
}
-->
</style></head>
<body topmargin="0">
<table width="900" height="25" border="0" align="center" cellpadding="0" cellspacing="0" bgcolor="#739E18">
<tr>
<td align="center" class="s1">上传文件管理 <a href=../upload/index.html>继续上传</a></td>
</tr>
</table>
<table width="900" border="0" align="center" cellpadding="0" cellspacing="0" bgcolor="#333333">
<tr>
<td><table width="100%" border="0" cellpadding="1" cellspacing="1">
<tr>
<td height="30" colspan="6" bgcolor="#EFEFE7"> <span class="s2">上传文件列表</span></td>
</tr>
<?php
$querysql="select * from cr_uploadfile";
$result=$db->query($querysql);
$total=mysql_num_rows($result);//取得信息总数
/*调用pageft(),每页显示10条信息(使用默认的20时,可以省略此参数),
使用本页URL(默认,所以省略掉)。*/
pageft($total,10);
//使用全局变量
$result=$db->query("select * from cr_uploadfile order by f_id desc limit $firstcount,$displaypg ");
while($rows=$db->loop_query($result)){
?>
<tr>
<td height="25" align="left" bgcolor="#EFEFE7"> ID:<?php echo $rows[f_id];?></td>
<td height="25" align="left" bgcolor="#EFEFE7"> 文件名称:<a title="点击查看该图片" href=<?php echo $rows[f_save];?> target="_blank"><?php echo $rows[f_name];?></a> </td>
<td align="left" bgcolor="#EFEFE7"> 状态:
<?php
if($rows[f_status]==0)
echo"<font color=red>未通过</font>";
else
echo"<font color=red>已通过</font>";
?></td>
<td height="25" align="left" bgcolor="#EFEFE7"> 上传时间:<?php echo $rows[f_date];?></td>
<td height="25" align="center" bgcolor="#EFEFE7"> <a href="../upload/delfile.php?id=<?php echo $rows[f_id];?>">删除该文件</a><?php
if($rows[f_status]==0)
echo"/<a href=filepass.php?id=$rows[f_id]>通过审核</a>";
?></td>
</tr>
<?
}
?>
</table></td>
</tr>
</table>
<table width="900" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td height="50" align="center">
<?php
//输出分页导航条代码:
echo $pagenav;
?></td>
</tr>
</table>
</body>
</html>
<?php
//为了避免重复包含文件而造成错误,加了判断函数是否存在的条件:
if(!function_exists(pageft)){
//定义函数pageft(),三个参数的含义为:
//$totle:信息总数;
//$displaypg:每页显示信息数,这里设置为默认是20;
//$url:分页导航中的链接,除了加入不同的查询信息“page”外的部分都与这个URL相同。
// 默认值本该设为本页URL(即$_SERVER["REQUEST_URI"]),但设置默认值的右边只能为常量,所以该默认值设为空字符串,在函数内部再设置为本页URL。
function pageft($totle,$displaypg=20,$url=''){
//定义几个全局变量:
//$page:当前页码;
//$firstcount:(数据库)查询的起始项;
//$pagenav:页面导航条代码,函数内部并没有将它输出;
//$_SERVER:读取本页URL“$_SERVER["REQUEST_URI"]”所必须。
global $page,$firstcount,$pagenav,$_SERVER;
//为使函数外部可以访问这里的“$displaypg”,将它也设为全局变量。注意一个变量重新定义为全局变量后,原值被覆盖,所以这里给它重新赋值。
$GLOBALS["displaypg"]=$displaypg;
if(!$page) $page=1;
//如果$url使用默认,即空值,则赋值为本页URL:
if(!$url){ $url=$_SERVER["REQUEST_URI"];}
//URL分析:
$parse_url=parse_url($url);
$url_query=$parse_url["query"]; //单独取出URL的查询字串
if($url_query){
//因为URL中可能包含了页码信息,我们要把它去掉,以便加入新的页码信息。
//这里用到了正则表达式
$url_query=ereg_replace("(^|&)page=$page","",$url_query);
//将处理后的URL的查询字串替换原来的URL的查询字串:
$url=str_replace($parse_url["query"],$url_query,$url);
//在URL后加page查询信息,但待赋值:
if($url_query) $url.="&page"; else $url.="page";
}else {
$url.="?page";
}
//页码计算:
$lastpg=ceil($totle/$displaypg); //最后页,也是总页数
$page=min($lastpg,$page);
$prepg=$page-1; //上一页
$nextpg=($page==$lastpg ? 0 : $page+1); //下一页
$firstcount=($page-1)*$displaypg;
//开始分页导航条代码:
$pagenav="显示第 <B>".($totle?($firstcount+1):0)."</B>-<B>".min($firstcount+$displaypg,$totle)."</B> 条记录,共 $totle 条记录<BR>";
//如果只有一页则跳出函数:
if($lastpg<=1) return false;
$pagenav.=" <a href='$url=1'>首页</a> ";
if($prepg) $pagenav.=" <a href='$url=$prepg'>前页</a> "; else $pagenav.=" 前页 ";
if($nextpg) $pagenav.=" <a href='$url=$nextpg'>后页</a> "; else $pagenav.=" 后页 ";
$pagenav.=" <a href='$url=$lastpg'>尾页</a> ";
//下拉跳转列表,循环列出所有页码:
$pagenav.=" 到第 <select name='topage' size='1' >n";
for($i=1;$i<=$lastpg;$i++){
if($i==$page) $pagenav.="<option value='$i' selected>$i</option>n";
else $pagenav.="<option value='$i'>$i</option>n";
}
$pagenav.="</select> 页,共 $lastpg 页";
}
}
?>
<?php
/*****************************************
Title :文件上传详解
Author:leehui1983(辉老大)
Finish Date :2006-12-28
*****************************************/
$uploaddir = "./files/";//设置文件保存目录 注意包含/
$type=array("jpg","gif","bmp","jpeg","png");//设置允许上传文件的类型
$patch="http://127.0.0.1/cr_downloadphp/upload/files/";//程序所在路径
//获取文件后缀名函数
function fileext($filename)
{
return substr(strrchr($filename, '.'), 1);
}
//生成随机文件名函数
function random($length)
{
$hash = 'CR-';
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
$max = strlen($chars) - 1;
mt_srand((double)microtime() * 1000000);
for($i = 0; $i < $length; $i++)
{
$hash .= $chars[mt_rand(0, $max)];
}
return $hash;
}
$a=strtolower(fileext($_FILES['file']['name']));
//判断文件类型
if(!in_array(strtolower(fileext($_FILES['file']['name'])),$type))
{
$text=implode(",",$type);
echo "您只能上传以下类型文件: ",$text,"<br>";
}
//生成目标文件的文件名
else{
$filename=explode(".",$_FILES['file']['name']);
do
{
$filename[0]=random(10); //设置随机数长度
$name=implode(".",$filename);
//$name1=$name.".Mcncc";
$uploadfile=$uploaddir.$name;
}
while(file_exists($uploadfile));
if (move_uploaded_file($_FILES['file']['tmp_name'],$uploadfile)){
if(is_uploaded_file($_FILES['file']['tmp_name']){
//输出图片预览
echo "<center>您的文件已经上传完毕 上传图片预览: </center><br><center><img src='$uploadfile'></center>";
echo"<br><center><a href='history.go(-1)'>继续上传</a></center>";
}
else{
echo "上传失败!";
}
}
}
?>
看了标题你也许要说,留言本,很基本的东东啊!谁不会啊,还要用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杂志投稿,大家若是转载,还希望注明版权,谢谢!最后来个效果图~~~~
在原创那边写了几个php+ajax的应用例子,今天和新手谈谈smarty+xjax,希望对新手有帮助,xajax是用PHP写的ajax开发框架,可以生成JS代码,这样使用起ajax就比较简单了,今天结合模板引擎smarty,来实现一个检测用户名合法性的小程序,大家有兴趣的话还可以扩展这个程序到自己的应用中,嗯,这里写出核心代码,里面注释很详细,不过建议大家看之前还是看看这个http://blog.csdn.net/fhiesc/archive/2006/07/04/873441.aspx,相信你会很快明白xajax是什么东东,及如何使用,最后依然是效果图。好的,看代码吧:
<?php
/*****************************************
Title :smarty结合xajax检测用户名简单实例
Author:leehui1983(辉老大)
Finish Date :2006-12-09
*****************************************/
//为避免中文乱码,需要在 xajax.inc.php 需要改一下默认的encoding:define ('XAJAX_DEFAULT_CHAR_ENCODING', 'gbk' )UTF8编码格式文件不需要更改
require_once('./libs/Smarty.class.php');//包含smarty类库
require('./xajax/xajax.inc.php');//包含xajax类库
function checkusername($textvalue){//编写需要的PHP函数
$checkresult=($textvalue=='test' ? '<font color=red>该用户名已经注册</font>' :'<font color=red>可以注册</font>');
$objresponse=new xajaxResponse();//实例化xajaxresponse对象
$objresponse->addassign("result","innerHTML",$checkresult);//指定ID为result的元素中添加内容$checkresult
return $objresponse;//返回结果文本
}
$xajax=new xajax();//实例化xajax对象
$smarty=new Smarty();//实例化smarty对象
$smarty->template_dir = "./templates";//设置模板目录
$smarty->compile_dir = "./templates_c"; //设置编译目录
$smarty->caching = false; //设置缓存方式
/*****************************************************
左右边界符,默认为{},但实际应用当中容易与JavaScript
相冲突,所以建议设成<{}>或其它。
*****************************************************/
$smarty->left_delimiter = "<{";
$smarty->right_delimiter = "}>";
$xajax->registerFunction("checkusername");//注册checkusername函数
$xajax->processRequests();//调用xajax用于接管请求
$smarty->assign('xajax_javascript', $xajax->getJavascript('./xajax/'));//输出JS代码,注意('./xajax/')中参数为xajax.inc.php父目录,在同意目录下可不同填写,否则必须填写
$smarty->assign('title','smarty结合xajax检测用户名简单实例');//替换模板内容
$smarty->display('index.tpl');//显示模板内容
?>
模板代码:
<html>
<head>
<meta http-equiv="Content-Type" c />
<title><{$title}></title>
<{$xajax_javascript}><{*使smarty支持xajax*}>
</head>
<body>
<form name="check" >
请输入用户名:
<input type="text" name="username" />
<input type="button" name="button" value="检查用户名" />
<div id="result"></div>
</form>
</body>
</html>
是不是不错?喜欢就顶吧~~~~~~~
效果图:
由于大4了,接下来要忙找工作和学校一些繁琐的事情,接下来的1,2个月可能没有时间写原创作品,今晚再弄一个,希望大家喜欢,别忘了支持我哦!^_^。这次给大家展示的是非常常用的一个ajax功能--联动下拉列表,本程序采用2级联动,根据数据库的内容用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 getclass(obj){
var pid=document.form1.select1.value;
document.getElementById(obj).innerHTML="<option>loading...</option>";
send_request('doclass.php?pid='+pid);
reobj=obj;
}
这个程序的核心就是动态添加
<option>......</option>
服务器端是进行数据的检索,很简单: