Chinaunix首页 | 论坛 | 博客
  • 博客访问: 17721534
  • 博文数量: 7460
  • 博客积分: 10434
  • 博客等级: 上将
  • 技术积分: 78178
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-02 22:54
文章分类

全部博文(7460)

文章存档

2011年(1)

2009年(669)

2008年(6790)

分类:

2008-04-14 15:54:16

扩展相册

  使用 Sajax 把我们的相册变成的 Web 应用程序如此轻而易举,我们要再花点时间添加一些功能,进一步说明 Sajax 如何使从服务器检索数据变得完全透明。我们将为相册添加元数据功能,这样用户就能为他们的图片添加说明。

  元数据

  没有上下文说明的相册是不完整的,比如照片的来源、作者等。为此我们要将图像集中起来创建一个简单的 XML 文件。根节点是 gallery,它包含任意多个 photo 节点。每个 photo 节点都通过其 file 属性来编号。在 photo 节点中可以使用任意多个标记来描述照片,但本例中只使用了 date、locale 和 comment。

  清单 12. 包含元数据的 XML 文件

<?xml version="1.0"?>
<gallery>
 <photo file="image01.jpg">
  <date>August 6, 2006</date>
  <locale>Los Angeles, CA</locale>
  <comment>Here's a photo of my favorite celebrity</comment>
 </photo>
 <photo file="image02.jpg">
  <date>August 7, 2006</date>
  <locale>San Francisco, CA</locale>
  <comment>In SF, we got to ride the street cars</comment>
 </photo>
 <photo file="image03.jpg">
  <date>August 8, 2006</date>
  <locale>Portland, OR</locale>
  <comment>Time to end our road trip!</comment>
 </photo>
</gallery>

  文件的解析不在本文讨论范围之列。我们假设您能够熟练使用 中众多 XML 解析方法中的一种。如果不熟悉的话,建议阅读 参考资料中的文章。我们不再浪费时间解释如何将该文件转化成 HTML,作为一个练习,读者可以自己了解下面的代码如何使用 XML 文件并生成 HTML。清单 13 中的代码使用了 PHP V5 中自带的 SimpleXML 包。

  清单 13. 元数据函数

function get_meta_data ( $file ) {

 // Using getimagesize, the server calculates the dimensions
 list($width, $height) = @getimagesize("images/$file");
 $output = "<p>Width: {$width}px, Height: {$height}px</p>";

 // Use SimpleXML package in PHP_v5:
 //
 $xml = simplexml_load_file("gallery.xml");

 foreach ( $xml as $photo ) {
  if ($photo['id'] == $file) {
   $output .= !empty($photo->date) ? "<p>Date taken:{$photo->date}</p>" : '';
   $output .= !empty($photo->locale) ? "<p>Location:{$photo->locale}>/p>" : '';
   $output .= !empty($photo->comment) ? "<p>Comment:{$photo->comment}</p>" : '';
  }
 }
 return $output;

  要注意的是,get_meta_data() 函数中还使用 getimagesize()(一个核心 PHP 函数,不需要 GD)计算图像的大小。

  再回到 get_image() 函数,它包含由 get_image_list() 生成的文件名的列表。查找元数据只需要将文件名传递给该函数即可。

  清单 14. 添加元数据

function get_image ( $index ) {
 $images = get_image_list ( 'images' );

 // ...

 $output .= '<img src="images/' . $images[$index] . '" />';
 $output .= '<div id="meta_data">' .
 get_meta_data( $images[$index] ) . '</div>';
 return $output;
}

  重新打开页面将看到服务器请求的结果。图 7 显示了带有元数据的放大的图像。


  结束语

  我们看到,使用 Sajax 可以消除客户机和服务器之间的障碍,程序员能够进行无缝远程函数调用而不用担心传输层、HTTP GET 和 POST 请求。我们可以花更多时间编写提供数据的 PHP 脚本以及表示层和控制层的 Javascript。在这个相册例子中,我们让客户机直接连接到图像。通过添加简单的元数据,我们看到让用户直接访问服务器上的信息是多么简单,无需担心协议的问题。

  与所有的 应用程序一样,我们的相册也有一个致命的弱点:没有使用浏览器的 “访问历史”,因为破坏了后退按钮的功能。在 “利用 PHP 开发 Ajax 应用程序” 系列的第 2 部分中,我们将通过实现历史记录缓冲和状态跟踪机制来解决这个问题。

阅读(191) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~