我已经阅读了许多类似的问题,并尝试将其放在我的网站上,但它不起作用(当您单击链接时,控制台上没有响应,数据库也没有更新)。
以下是我想做的:我希望用户通过单击评论旁边的图标来+1
评论进行评分。我希望它更新我的 mysql comment_table
名为 rating
的列 rating+1
.当我在没有 AJAX 的情况下执行此操作时(即,只需将表单操作设置为 php page?id=10
),它工作正常。不过,我无法让 AJAX 更新数据库。
我的主页上有评论:
<a href="javascript:void(0);" onClick="updateRating(1,<?php echo $thisperspective_row['id']; ?>)" alt="UPVOTE" id="upvote_<?php echo $thisperspective_row['id']; ?>"><span class="glyphicon glyphicon-chevron-up"></span></a>
该链接下方的javascript:
<script type="text/javascript">
function updateRating(rating, id){
$.ajax({
type: "GET",
url: "rating.php",
mode: "vote",
rating: rating,
id: <?php echo $thisperspective_row['id']; ?>,
success: function(response) {
console.log(response);
}
});
return false; // Prevent the browser from navigating to the-script.php
};
</script>
我的评分.php文件是
<?php
require_once('connectiontodatabase.php');
/* simple comment up and down voting script */
$mode = $_GET['mode'];
$rating = $_GET['rating'];
$id = $_GET['id'];
if ($mode=="vote")
{
// The name of the
$cookie = "nameofmycookie".$id;
if(isset($_COOKIE[$cookie]))
{
echo '<div class="alert alert-warning"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> Sorry You have already rated this comment within the last 14 days.</div>';
}
else
{
$expiry = 1209600 + time(); // 14 day expiry
setcookie ($cookie, "voted", $expiry);
mysql_query ("UPDATE comment_table SET rating = rating+$rating WHERE id=$id", $connection);
}
}
?>
当我查看源代码时,php 运行良好,所有变量都正确列出。但是,当我单击链接时,根本没有响应,控制台也不会输出响应。我做错了什么?提前感谢!
首先,
您应该更改检测点击事件的方式。看看这个小提琴。其次,您需要使用 data 选项在一个 JSON 字符串中传递所有变量。您的代码应如下所示:
<span class="glyphicon glyphicon-chevron-up clickable"
data-rating="1"
data-id="<?php echo $thisperspective_row['id']; ?>"></span>
<script type="text/javascript">
$('.clickable').on('click', function() {
var data = {
mode: "vote",
rating: $(this).data('rating'),
id: $(this).data('id')
};
$.ajax({
type: 'GET',
url: 'rating.php',
data: data,
success: function(response) {
console.log(response);
}
});
});
</script>
首先,检查你是否正在加载jQuery,然后使用此代码
function updateRating(rating, id){
$.ajax({
type: "GET",
url: "rating.php",
mode: "vote",
data: { rating: rating, id: id },
success: function(response) {
console.log(response);
}
});
return false; // Prevent the browser from navigating to the-script.php
};
正在为我工作。请注意,我在 Ajax 内部删除了 ',因为您已经在函数中发送参数,因此要发送参数,您必须使用 data:,您可以在此处查看更多示例 Ajax jQuery