表单下面的 Add Comment 按钮将调用 addcomment() JavaScript 函数。这个函数使用了 Prototype.js 库中的 Ajax.Updater 对象来调用 addcomment.php 脚本。它使用了非常方便的 serialize() 函数对名称、电子邮件地址和评论内容进行打包,这个函数也是由 Prototype.js 提供的。
如果评论成功,代码会重置评论字段的文本,这样可以允许用户随意添加任意数量的评论,而不用重新输入名称和电子邮件地址。
清单 8 显示了 addcomment.php 脚本。 清单 8. addcomment.php<?php require_once("DB.php"); $id = $_POST['id']; $db =& DB::Connect( 'mysql://root@localhost/comments', array() ); if (PEAR::isError($db)) { die($db->getMessage()); } $sth = $db->prepare( 'INSERT INTO comments VALUES ( ?, ?, ?, ? )' ); $db->execute( $sth, array( $id, $_POST['email'], $_POST['name'], $_POST['comment' ] ) ); $res = $db->query('SELECT * FROM comments WHERE movie_id=?', $id ); while( $res->fetchInto( $row ) ) { ?> <div> <a href="mailto:<?php echo($row[1]) ?>"><?php echo($row[2]) ?></a> says: '<?php echo($row[3]) ?>' </div> <?php } ?>
首先,脚本将 POST 数据中指定的评论内容添加到数据库中。然后,将所有的评论内容作为 HTML 代码输出,其方式与原始评级页面一样,只不过这次页面中额外显示了用户所提供的评论。
新的评级页面如 图 4 所示。图 4. 更新后的评级页面,具有评论功能。
这个评论系统可以即时地向用户反馈信息。用户单击 Add Comment 时,页面会立即更新评论内容。系统还可以显示出其他用户在这期间提交的评论。
您可能需要扩展这个示例,使服务器可以自动更新评论部分。当然,您大可不必调用 addcomment.php 来完成这点。可以使用另一个脚本来返回评论,而不必添加新脚本。为此,Prototype.js 提供了一个 Ajax.PeriodicalUpdater 类,使用这个类中定义的 ID、刷新率和 URL 可以根据需要刷新 Web 页面中的任何部分。
添加 RSS 提要
扩展该示例的另一种简单的方法是将电影列表的内容和排名作为 RSS 导出。实现这一功能的代码如 清单 9 所示。
清单 9. rss.php<?php header( "content-type:text/xml" ); ?> <rss version="0.91"> <channel> <title>Movie rankings</title> <link>http://localhost/comments/rss.php</link> <?php require_once("DB.php"); $db =& DB::Connect( 'mysql://root@localhost/comments', array() ); if (PEAR::isError($db)) { die($db->getMessage()); } $res = $db->query( 'SELECT * FROM movies' ); while( $res->fetchInto( $row ) ) { $res2 = $db->query( 'SELECT count( rating ), sum(rating ) FROM ratings WHERE movie_id=?', $row[0] ); $rating = 0.0; while( $res2->fetchInto( $row2 ) ) { if ( $row2[0] > 0 ) $rating = $row2[1] / $row2[0]; } ?> <item> <title><?php echo($row[1]) ?> - <?php echo( $rating > 0 ? $rating : 0 ) ?> stars</title> <link>http://localhost/commentsts/rate2.php?id=<?php echo($row[0]) ?></link> <description><?php echo($row[1]) ?></description> </item> <?php } ?> </channel> </rss>
清单 9 中的代码的作用类似于使用 HTML 格式导出数据。它使用 <title>、<description> 和 <link> 标记指向各个电影页面,而不是 HTML 中的 <table>、<tr> 和 <td> 标记。当我在 Firefox 浏览器中打开这个页面时,所显示的页面如 图 5 所示。
图 5. 浏览器中的 RSS 提要
很容易吧!从 PHP 中获取 XML 提要就是这么简单。
当我使用以下命令行在本地运行代码时:
% php rss.php
我可以直接看到 RSS XML。清单 10 显示了这个 RSS 的一部分。
清单 10. RSS excerpt<rss version="0.91"> <channel> <title>Movie rankings</title> <link>http://localhost/comments/rss.php</link> <item> <title>Star Wars - 4.5 stars</title> <link>http://localhost/commentsts/rate2.php?id=1</link> <description>Star Wars</description> </item> <item> ...
结束语
最近,关于用户生成内容的话题格外引人关注,尤其是它如何增强 Web 2.0 的力量这方面。与本文中示例一样,您可以使用 Prototype.js 库之类的优秀工具轻易地构建 Ajax 应用程序。对网站内容的评级和评论功能确实是一种极好的用户生成内容的形式。
(编辑:aniston)
|