您肯定需要同时使用 javascript 和 PHP 来完成此操作。
我会这样处理它:
a) 使用 jQuery javascript 库使 javascript 更容易。
b) 编写一些响应用户选择评级的 javascript。您可能需要绑定到评分按钮的 onClick 事件。
c) 单击评分按钮时,javascript 函数应使用 jQuery.ajax 通过 HTTP POST 将所选评分发送到服务器。发送到服务器的数据可能需要包含一个标识电影的 ID、一个代表用户的 ID(这样您就可以阻止人们为同一部电影多次投票)以及他们选择的评分。
d) 在服务器端,您可以编写一个 PHP 脚本来处理投票提交。它会检查电影和用户 ID(存储在 PHP 的 $_POST 变量中),然后将评分保存到某个数据库中。然后它还可以将包含下一个电影 ID 和下一个海报的响应发送回客户端。我建议您使用 json_encode 以一种易于 javascript 解释的方式存储此信息。
e) 最后,回到客户端,您的 javascript 代码可以对 PHP 发回的数据做出反应,方法是发出“谢谢您的投票”之类的消息,然后在屏幕上更改电影详细信息以替换它们用新的。
您的客户端代码看起来有点像这样:
<img id="movie-poster" src="movie poster src" />
<ul>
<li class="rating-button">1</li>
<li class="rating-button">2</li>
<li class="rating-button">3</li>
<li class="rating-button">4</li>
<li class="rating-button">5</li>
</ul>
<script>
var currentUserId;
var currentMovieId;
$('.rating-button').on('click',function() {
$.ajax({
url: "URL of PHP script here",
type: 'post',
data: {'movieId':currentMovieId, 'userId':currentUserId, 'rating':$(this).text()},
dataType: 'json',
success: function(response) {
// this runs after your PHP script has responded
// update your page with the new movie here
alert('thanks for voting');
currentMovieId = response.newMovieId;
$('#movie-poster').attr('src',response.newMoviePosterSrc);
}
});
}
</script>
您的 PHP 脚本看起来有点像这样(您必须自己弄清楚所有数据库和用户身份验证位)
<?php
$user_id = $_POST['userId'];
$movie_id = $_POST['movieId'];
$rating = $_POST['rating'];
// check that the user is allowed to vote - possibly examine cookie for this
// check that rating is between 0 and 5
// check that the movie exists
// store results of vote in database
// load up another random movie from the database and send it back (in JSON format)
// assume details of new movie are in $new_movie =
header('Content-type: application/json');
echo json_encode(array('newMovieId'=> new movie id here, 'newMoviePosterSrc' => URL of new poster here));
exit;
您还应该为该代码添加一些错误处理。例如,如果出现连接问题或无法识别电影 ID 或其他问题时显示的消息。
此页面包含有关如何从数据库中选择随机行的更多信息 - IE 以随机选择下一张要显示的海报:
How to randomly select rows in SQL?
希望这足以让您入门。