


Smarty combined with Ajax to implement a non-refresh guestbook example_PHP tutorial
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";
?>
<{section name=loop loop=$bookinfo}><{*循环显示留言*}>
用户名:<{$bookinfo[loop].username}> 内容:<{$bookinfo[loop].comment}>
<{/section}>
模板中的内容在<{}>中的一会会被PHP替换掉,这就实现了美工和程序员的分工,不错吧有关Smarty的内容还请参考手册,这里就不便多说。来看下页面是怎么输出模板的吧:
php "; '
/*****************************************
Title:Smarty combined with Ajax message board
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
$db = new db() ;//Generate database operation instance
$smarty = new Smarty();//Instantiate the smarty object
$smarty->template_dir = "./templates";//Settings
$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
}
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.="
}
//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

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Is the F5 key not working properly on your Windows 11/10 PC? The F5 key is typically used to refresh the desktop or explorer or reload a web page. However, some of our readers have reported that the F5 key is refreshing their computers and not working properly. How to enable F5 refresh in Windows 11? To refresh your Windows PC, just press the F5 key. On some laptops or desktops, you may need to press the Fn+F5 key combination to complete the refresh operation. Why doesn't F5 refresh work? If pressing the F5 key fails to refresh your computer or you are experiencing issues on Windows 11/10, it may be due to the function keys being locked. Other potential causes include the keyboard or F5 key

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

How to implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

In today's software development field, Golang (Go language), as an efficient, concise and highly concurrency programming language, is increasingly favored by developers. Its rich standard library and efficient concurrency features make it a high-profile choice in the field of game development. This article will explore how to use Golang for game development and demonstrate its powerful possibilities through specific code examples. 1. Golang’s advantages in game development. As a statically typed language, Golang is used in building large-scale game systems.

PHP Game Requirements Implementation Guide With the popularity and development of the Internet, the web game market is becoming more and more popular. Many developers hope to use the PHP language to develop their own web games, and implementing game requirements is a key step. This article will introduce how to use PHP language to implement common game requirements and provide specific code examples. 1. Create game characters In web games, game characters are a very important element. We need to define the attributes of the game character, such as name, level, experience value, etc., and provide methods to operate these

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:
