我正在为报价创建一个类似的计数器。当用户单击“喜欢”按钮并显示“喜欢”次数时,我试图增加“喜欢”计数器。
我遇到的问题:
当我刷新页面时,类似计数器会增加(不是因为我实际上被按下了“赞”按钮)。
我尝试实时实现jQuery来更新like计数器,但失败了:(
我提到了与此相关的所有QnA,找不到所需的解决方案。我经历了这个[问题] PHP/MySQL Like Button,并进行了必要的更改,但是当我单击按钮时,数据库中没有更新。
This is the code for one quote.
<div class="testimonial text-sm is-revealing">
<div class="testimonial-inner">
<div class="testimonial-main">
<div class="testimonial-body">
<p id="q1">
<?php
$sql = "select quotes from voted where voted.quote_id = 1";
$result = mysqli_query($link,$sql);
$row = mysqli_fetch_array($result);
echo "$row[0]";
?></p>
</div>
</div>
<div class="testimonial-footer">
<div class="testimonial-name">
<button method="POST" action='' name="like" type="submit" class="like"><b>Like</b></button>
<?php
if(isset($_POST['like'])){
$link = mysqli_connect("localhost","root","","success");
$sql = "UPDATE voted SET likes = likes+1 WHERE voted.quote_id = 1";
$result = mysqli_query($link,$sql);
}
?>
<label>
<?php
$link = mysqli_connect("localhost","root","","success");
$sql = "SELECT likes from voted WHERE voted.quote_id = 1";
$result = mysqli_query($link,$sql);
$row = mysqli_fetch_array($result);
echo "$row[0]";
?>
</label>
<button class="btn" id="clipboard" onclick="copyFunction('#q1')"></button>
</div>
</div>
</div>
当我点击“赞”按钮时,如何制作“赞”计数器工具?
我该如何实现jQuery和AJAX,以便在不刷新页面的情况下更新计数器?
请原谅我糟糕的代码结构。
感谢您的帮助。
答案 0 :(得分:3)
要使异步设置正常运行,您需要三件事:
您的后端PHP脚本如下所示(async.php):
<?php
if(isset($_POST['get_quotes'])) {
$sql = "select quotes from voted where voted.quote_id = 1";
$result = mysqli_query($link,$sql);
$row = mysqli_fetch_array($result);
echo "$row[0]";
}
if(isset($_POST['like'])) {
$link = mysqli_connect("localhost","root","","success");
$sql = "UPDATE voted SET likes = likes+1 WHERE voted.quote_id = 1";
$result = mysqli_query($link,$sql);
}
?>
您的前端页面将包含一个具有ID以便与JQuery挂钩的元素,以及一个具有类或ID的按钮以捕获单击事件(page.html):
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="core.js"></script>
<body>
<button id="increment-like" value="Like" type="button" />
<p id="like-count">
</p>
</body>
<html>
最后,对于使用JQuery(core.js)的基本ajax请求,您的JavaScript文件应如下所示:
$(document).ready(function() {
// initially grab the database value and present it to the view
$('#like-count').text(getDatabaseValue());
$('#increment-like').on('click', function() {
incrementDatabaseValue();
});
});
function getDatabaseValue() {
$.post("async.php",
{
get_quotes: true
},
function (data, status) {
// check status here
//return value
return data;
});
}
function incrementDatabaseValue() {
$.post("async.php",
{
like: true
},
function (data, status) {
// check status here
// update view
$('#like-count').text(getDatabaseValue());
});
}
我尚未测试此代码,但它应该足够清晰,详细,以使您步入正轨。