|
清单 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: // http://us3.PHP.net/manual/en/ref.simpleXML.php $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="http://www.ASPcool.com/lanmu/images/' . $images[$index] . '" />'; $output .= '<div id="meta_data">' . get_meta_data( $images[$index] ) . '</div>'; return $output; } 重新打开页面将看到服务器请求的结果。图 7 显示了带有元数据的放大的图像。 图 7. 使用元数据的相册 结束语 我们看到,使用 Sajax 可以消除客户机和服务器之间的障碍,程序员能够进行无缝远程函数调用而不用担心传输层、HTTP GET 和 POST 请求。我们可以花更多时间编写提供数据的 PHP 脚本以及表示层和控制层的 JavaScript。在这个相册例子中,我们让客户机直接连接到图像数据库。通过添加简单的元数据,我们看到让用户直接访问服务器上的信息是多么简单,无需担心协议的问题。 与所有的 Ajax 应用程序一样,我们的相册也有一个致命的弱点:没有使用浏览器的 “访问历史”,因为破坏了后退按钮的功能。在 “利用 PHP 开发 Ajax 应用程序” 系列的第 2 部分中,我们将通过实现历史记录缓冲和状态跟踪机制来解决这个问题。 |