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

Smarty combined with Ajax to implement a non-refresh guestbook example_PHP tutorial

WBOY
Release: 2016-07-21 15:58:07
Original
776 people have browsed it

After reading the title, you might say, guestbook, it’s very basic! Who doesn’t know how to use Smarty? Isn’t this tiring? Don't worry, what I want to express is a programming thought and structure, not to prove how meaningful what I do is. I believe it will inspire beginners to learn Smarty and ajax. It was originally done with ajax, but unfortunately the debugging was never successful, so I had to do it by handwriting JS. But it doesn't matter, it still has some value. Please download the source code to read the site structure yourself. The code is not long, so it shouldn’t be annoying. ^_^ Please listen to me and explain it slowly.
Now that PHP5 is available, OO (object-oriented) is very popular, so don’t miss it here. First, let’s take a look at how we use OO to implement database operations and connections:
[php]
/**************************

Page: dbclass.php
Author: Hui Boss
Function: Define database operations Class
**************************/
php
/**************************

Page: dbclass.php
Author: Hui Boss
Function: Define database operations Class
**************************/
class db
{
 
//Create a constructor, its function is to connect to the database and select the corresponding database
 
public function __construct
(){
require(
'config.inc.php'
);
🎜>
$dbhost,$dbuser,$dbpassword) or die( "error!"); "
);                                                                   🎜>);
}
//Execute SQL statement function
public function query
($sql){
return $sql

);
}

//Get the result set array function >public function loop_query($result
){
return
mysql_fetch_array ($result
);
}
// Create a destructor, function: close the database connection
public function __destruct(){ return
mysql_close
(); } }?> This class What are its characteristics? First, let’s introduce that __construct() is a constructor function. What is a constructor function? In layman's terms, it is a function that is automatically executed after a class is instantiated. What is __destruct()? It is a destructor. Its function is to automatically destroy the object when there is no method pointing to the object. It usually contains some finishing operations, such as closing files, closing database connections, etc. Do you understand when you see this? Some? That's right!在类实例化的时候自动执行带有数据库连接方法的构造函数,在实例销毁的时候执行关闭数据库连接的析构函数,对于一些基本数据操作我们只要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}>



  
   
      
      
   
   
      
      
   
  
用户名:
留言内容:

  
  




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

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

require('./libs/Smarty.class.php');
/ /Include smarty class library
require('./inc/dbclass.php');
//Contains database operation class

$db = new db() ;
//Generate database operation instance
$smarty = new Smarty();
//Instantiate the smarty object
$smarty->
template_dir = "./templates";//SettingsTemplateDirectory
$smarty->compile_dir = "./templates_c";
//Set the compilation directory
$smarty->caching = false;
//Set cache method
/*************** ******************************************
Left and right boundary characters, the default is {}, However, in actual applications, it is easy to conflict with JavaScript
, so it is recommended to set it to <{}> or others.
*********************************************** ******/
 
$smarty->left_delimiter "< {"
; 🎜>
"}>"
; $smarty->assign
(
'title'
,'Smarty combined with ajax to create a simple message board');//Replace template content //Set 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"=>$rs['comment' ]); } $smarty->
assign(

"bookinfo"
,$array); unset ($array);
//Destroy array variable
$smarty->display
(
"index.tpl"
);//Compile and display located The index.tpl template under ./templates ?> has a lot of comments on the page examples. Please refer to the Smarty manual
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 Briefvar http_request= false;
function send_request(url){//Initialization, specify processing function, function to send request
http_request=false;//Start initializing XMLHttpRequest objectif(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, create object instance Failure
window.alert("Failed to create XMLHttp object!");
return false;
}
http_request.onreadystatechange=processrequest;
//Determine the request method, URL, and whether to execute the next code synchronously
http_request.open("GET" ,url,true);
http_request.send(null);
}
//Function to process the returned information
function processrequest(){
if(http_request.readyState==4) {//Determine the 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 abnormal
alert("The page you requested is not normal!");
}
}
}
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;
}
}

In this way, when we click the "Publish" button, the data will be processed asynchronously by the server, and asynchronous updates will be organized through JS. You will be able to see it immediately after sending the message. Instead of waiting for the traditional page to jump, see 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');
//Contains database operation class
$ 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 message list for real-time updates
//$arr.="Username: {$rows['username']} Content: { $rows['comment']}

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

';
}
//echo $arr;

?>


Well, first insert the data, and then organize and display the updated data 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 a rendering~~~~

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/317700.htmlTechArticleAfter reading the title, you may say, guestbook, very basic stuff! Who doesn’t know how to use Smarty? Isn’t this tiring? Don't worry, what I want to express is a programming idea and structure, not...
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