PHP的PEAR::HTML_AJAX类库应用
HTML_AJAX下载:http://pear.php.net/package/HTML_AJAX/download
Pear:HTML_AJAX是一个相当成熟的Ajax框架, 使用JSON进行数据传输。內建丰富的例子,包括留言板、登录、grab…等等。
简单的例子:
You can use HTML_AJAX in many different ways but most setups use an instance of HTML_AJAX_Server to deliver both the javascript libraries and to handle AJAX requests from browsers.
A basic server is shown below, in the file server.php:
<?php
//a session is required(you can also set session.auto_start=1 in php.ini)
session_start();
include 'HTML/AJAX/Server.php';
$server = new HTML_AJAX_Server();
$server->handleRequest();
?>
This basic setup gives you access to the HTML_AJAX javascript libraries, which will allow you to do basic AJAX actions like replacing the content of a div with the output of a url on your server.
Let us now create a new webpage with a div container and a button. Whenever we push the button we want to fetch some data and update the div container. Save the file as page.html:
<html>
<script type="text/javascript" src="server.php?client=all"></script>
<div id="target">I'm the target</div>
<script type="text/javascript">
HTML_AJAX.replace('target','output.php');
</script>
<form>
<input type="button" onclick="HTML_AJAX.replace('target','output.php');" value="Update target">
</form>
</html>
This will load the content of output.php into the <div> with an ID of "target" when HTML_AJAX.replace() is called (i.e. when you push the button).
Now let's create the file that generates the dynamic stuff. It could be anything, like fetching stuff from a database or whatever. For now we are going to get the local time, and we do it in the file output.php:
<?php
print("<h1>". strftime("%H:%M:%S") ."</h1>");
?>
There! Each time you press Update target, the target is replaced with the current time. Now it's up to your imagination to use this to something more useful.