xajax+Smarty 新手入门之 HelloWorld
时间:2008-01-18 来源:alexru
前段时间因为项目需要开始接触 PHP 开发。本着简单、高效的原则,最终权衡,我选择 PEAR 和 Smarty 这些流行的第三方库来开发我的项目。现在项目基本完成了,也正式上线了。
有点可惜的是一直以来想在项目中应用 Ajax 的功能,无奈精力有限,上次做项目时没有同步加进来。希望这段时间有点精力,对 PHP, PEAR, Smarty 这方面也稍微熟悉了一点,不如学习和应用一下 Ajax 的功能吧。
第一个疑问:自己写 Ajax 代码还是选择已存在的 Ajax 框架或库?
我的回答,选择 Ajax 框架或库,这样能快速开发项目,自己写的未必比这些现存的好,在这里可不是否定你的水平,:) 毕竟这些框或库已经存在和完善许久了。如果自己对技术感兴趣,希望从自己一行一行代码写,OK!当你了解这些现在的 Ajax 框架后再回过头来看,我想这比你刚开始就自己写来更容易理解,对你没有坏处吧。
第二个疑问:目前流行的 Ajax 框架很多,我该选择哪个?
我的问题,我选择 xajax 库, 主要是因为它支持 Smarty 模板。今天下午查资料对几个流行 Ajax 框架比较一下,一看到 xajax 支持 Smarty 模板,好感顿由心生,用它吧。呵呵!
下面是我刚才学习和测试 xajax 和 Smarty 的步骤,希望对想学习的人有一些帮助,也希望各位朋友多多指点和交流。
1、Smarty 应用
下载:
Smarty 2.6.18 Source
安装:
Windows 安装步骤
我直接把目录下的 libs 拷贝到网站目录下并重命名 smarty,大家也可参照上面步骤。
示例代码:
index.php
require_once('./smarty/Smarty.class.php');
$smarty = new Smarty();
$smarty->template_dir = "./templates/";
$smarty->compile_dir = "./templates_c/";
$smarty->config_dir = "./configs/";
$smarty->cache_dir = "./cache/";
$smarty->assign('name','Hello World');
$smarty->display('index.tpl');
index.tpl
html>
body>
p>Hello, {$name}/p>
/body>
/html>
2. xajax 应用
下载:
xajax 0.2.5
安装:
如何安装
我直接把解压出来的 xajax 拷贝到网站目录下
示例代码:
index.php
?php
require_once('./xajax/xajax.inc.php');
function helloWorld()
{
$text = "Hello World";
$objResponse = new xajaxResponse();
$objResponse->addAssign("div1","innerHTML",$text);
return $objResponse;
}
$xajax = new xajax();
$xajax->registerFunction("helloWorld");
$xajax->processRequests();
?>
html>
head>
title>Hello World/title>
?php $xajax->printJavascript('./xajax/'); ?>
/head>
body>
div id="div1" name="div1">/div>
br/>
button onclick="xajax_helloWorld()" >Click Me/button>
/body>
/html>
3. 结合 xajax 和 Smarty 应用
示例代码:
index.php
?php
require_once('./xajax/xajax.inc.php');
function helloWorld()
{
$text = "Hello World";
$objResponse = new xajaxResponse();
$objResponse->addAssign("div1","innerHTML",$text);
return $objResponse;
}
$xajax = new xajax();
$xajax->registerFunction("helloWorld");
$xajax->processRequests();
$xajaxHead=$xajax->printJavascript('./xajax/');
require_once('./smarty/Smarty.class.php');
$smarty = new Smarty();
$smarty->template_dir = "./templates/";
$smarty->compile_dir = "./templates_c/";
$smarty->config_dir = "./configs/";
$smarty->cache_dir = "./cache/";
$smarty->assign('xajaxHead',$xajaxHead);
$smarty->display('index.tpl');
?>
index.tpl
html>
head>
title>Hello World/title>
{$xajaxHead}
/head>
body>
div id="div1" name="div1">/div>
br/>
button onClick="xajax_helloWorld()" >Click Me/button>
/body>
/html>
结束语
希望本文档有初学的朋友有些帮助,也希望各位朋友多多交流,大家共同进步!
相关阅读 更多 +
排行榜 更多 +