我使用jquery,html和php为我的页面创建了一个类似按钮。现在我试图读出喜欢的总量。
当我点击它时,它通过我的jquery和php并在我的控制台中返回总金额。但是在我更新页面之前,我无法在页面上看到它。
PHP和HTML
<?php
$page = new CMS();
$gp = $page->getPage();
foreach ($gp as $sp) {
//var_dump($sp);
echo "<div class='pub'>";
echo "<h4 class='pub-headline'>" . $sp['title'] . "</h4>";
echo "<article class='pub_art'>" . $sp['content'] . "</article>";
echo "<p class='pub_created'>" . $sp['created'] . "</p>";
echo "<p class='pub_created_by'>". $sp['writer'] ."</p>";
echo "<button class='show'>Show</button>";
echo "<button class='noshow'>Hide</button>";
echo "<div class='vote_widget'>";
echo "<div class='voting' onclick='vote(" . $sp['id'] . ", 1)'></div>";
echo"<div class='total_likes'>" . $sp['likes'] . "</div>";
echo"</div>";
echo "</div>";
}
?>
Jquery的
function vote(id, likes) {
$.post("classCalling4.php",
{ id: id, likes: likes }, function(result){
console.log(result)
$(".total_likes" + id) .html(result);
;
});
OOP PHP
public function updateLikes($id, $likes) {
$id = mysqli_real_escape_string($this->db, $id);
$likes = mysqli_real_escape_string($this->db, $likes);
$id = intval($id);
$likes = intval($likes);
$sql = "UPDATE pages
SET likes = likes+1
WHERE id = $id ";
$result = mysqli_query($this->db, $sql) or die("Fel vid SQL query 1"); // Hit kommer jag
$sql2 = "SELECT * from pages WHERE id = $id ";
$result2 = mysqli_query($this->db, $sql2) or die ("Fel vid SQL query 2");
$row = mysqli_fetch_array($result2);
$tot_likes = $row['likes'];
echo $tot_likes;
}
答案 0 :(得分:1)
你应该将id添加到类名,因为你在jquery脚本中假设这个:
$(".total_likes" + id) .html(result);
所以你的HTML应该是:
echo"<div class='total_likes".$sp['id']."'>" . $sp['likes'] . "</div>";
如果您使用此类来提供样式,则可以使用id:
替换该类echo"<div class='total_likes' class='total_likes".$sp['id']."'>".$sp['likes']."</div>";
你的javascript应该是:
$("#total_likes" + id) .html(result);
答案 1 :(得分:1)
由于total_likes
位于foreach
循环中,因此您应该将id
与类名相关联,以使其唯一。
所以,而不是
echo"<div class='total_likes'>" . $sp['likes'] . "</div>";
这样做
echo"<div class='total_likes'".$sp['id'].">" . $sp['likes'] . "</div>";