Home > Backend Development > PHP Tutorial > Smarty combined with Ajax to implement non-refresh guestbook example

Smarty combined with Ajax to implement non-refresh guestbook example

WBOY
Release: 2016-07-29 08:35:55
Original
919 people have browsed it

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



<{$title}>





<{*这里显示留言内容*}>
<{section name=loop loop=$bookinfo}><{*循环显示留言*}>
用户名:<{$bookinfo[loop].username}> 内容:<{$bookinfo[loop].comment}>


<{/section}>





< ;td width="80" height="30" align="center">Username:

"
"
" " ;td height="120">



php
/***************************************** Title:Smarty combined with Ajax message board
Example Author:leehui1983(Hui Boss)
Page Name:index.php
Finish Date:2006-12-17
************************* ****************/

require('./libs/Smarty.class.php ');
//Contains smarty class library
require('./inc/dbclass.php');
//Contains databaseoperation class
$db = new db();
//Generate database operation instance
$smarty = new Smarty();
//Instantiate smarty Object
$smarty->template_dir = "./templates";//Set template directory
$smarty-> compile_dir ="./templates_c";
//Set the compilation directory
$smarty->caching = false;
/ /Set cache method /************************************************ *********
Left and right boundary characters, the default is {}, but in actual applications it is easy to conflict with JavaScript
, so it is recommended to set it to <{}> or other.
*************************************************** ****/
$smarty->left_delimiter = "<{"
;
$smarty-> ;right_delimiter = "}>"
;
$smarty->assign('title','smarty combined with ajax to create a simple message board' );
//Replace template content
//Set the initial pagemessage content displayed by Smarty
$rt=$db->query(( "select * from bookinfo order by id desc"

);
while($rs=$db->loop_query($rt

)){
$array[]=array("username"=>$rs['username'],"comment"=&g t; $rs['comment'

]);
}
$smarty->assign("bookinfo", $array

);
unset ($array);

//Destroy array variable
$smarty->display("index.t pl");

//Compile and display the index.tpl template located under ./templates
?>

There are quite a lot of comments on the page examples. Please refer to the Smartymanual
This is So easy! ! Haha~~~~
Then it’s time to introduce ajax. Here we use a basic development framework to implement it. For knowledge about ajax, I suggest you take a look at the very popular online electronic tutorial Ajax Development Brief
var http_request=false;
function send_request(url){//Initialization, specify the processing function, the function to send the request
http_request=false;
//Start initializing the XMLHttpRequest object
if(window.XMLHttpRequest){//Mozilla browser
http_request=new XMLHttpRequest();
if(http_request.overrideMimeType){//Set MIME category
http_request.overrideMimeType("text/xml");
}
}
else if(window.ActiveXObject){//IE browser
try{
http_request=new ActiveXObject("Msxml2.XMLHttp");
}catch(e){
try{
http_request=new ActiveXobject("Microsoft.XMLHttp");
}catch(e){}
}
}
if(!http_request) {//Exception, failed to create object instance
window.alert("Failed to create XMLHttp object!");
return false;
}
http_request.>//Determine the request method, URL, and whether to execute the next code synchronously
http_request .open("GET",url,true);
http_request.send(null);
}
//Function that processes the returned information
function processrequest(){
if(http_request.readyState==4){//Judgement Object status
if(http_request.status==200){//The information has been returned successfully, start processing the information
document.getElementById(reobj).innerHTML=http_request.responseText;
}
else{//The page is not normal
alert( "The page you requested is abnormal! ");
}
}
}
function send(obj){
var f=document.book;
var username=f.username.value;
var comment=f.comment.value;
if(username== ""||comment==""){🎜 document.getElementById(obj).innerHTML="Please fill it out completely!";
return false;
}
else{
send_request('checkbookinfo.php?username='+username+'&comment='+comment);
reobj=obj;
}
}
This is how we click "Publish" button, the data will be processed asynchronously by the server, and asynchronous updates will be organized through JS. After sending a message, you will be able to see your message immediately instead of waiting for the traditional page to jump. So where is the data sent for processing? ?Look here:
php
/*****************************************
Title: Smarty combined with Ajax message board example
Author :leehui1983(Hui Boss)
Page Name:checkbookinfo.php
Finish Date :2006-12-17
*************************** **************/
header("Content-type: text/html;charset=GBK" );
//Output encoding to avoid Chinese garbled characters
include('./inc/dbclass.php');
//Include database operation classes
$ db=new db();
//Generate database operation instance
$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)){
//Print the message list for real-time updates
//$arr.="Username: {$rows['username']} Content: {$rows['comment']}

";
echo ' Username: '.$rows['username'].' Content: '.$rows [ 'comment'].'

';
}
//echo $arr;
?>

Well, insert the data first , in general The updated data is organized and displayed through JS, AJAX looks really good! That’s basically the introduction. I wonder if you have ever thought about what can be changed by adding an iframe? Yes! No refresh chat room, use your ability to achieve a look. This example uses OO, AJAX, and SMARTY. There are quite a lot of things. I hope you all like it. I have decided to submit this article to PHP Magazine. If you reprint it, please indicate the copyright. Thank you! Finally, here is the effect picture~~~~

The above has introduced an example of Smarty combined with Ajax to implement a non-refresh guestbook, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template