gpt4 book ai didi

javascript - AJAX 响应应更新 while 循环结果中的所有记录

转载 作者:行者123 更新时间:2023-12-01 02:42:19 28 4
gpt4 key购买 nike

我绞尽脑汁,但无法得到想要的结果。
在 while 循环中,所有评论都被获取。每个评论都有一个带有 Font Awesome 星号的按钮,可以使该评论成为最爱。我想在鼠标悬停在任何评论的星形按钮上时显示登录用户最喜欢的评论总数。 (这样用户就可以知道到目前为止我收藏了多少条评论。

我正在使用 jQuery AJAX 方法来更新收藏评论的记录。
一切都运行良好,最喜欢的评论正在 mysql 记录中更新,并且 AJAX 响应运行良好。

我的实际问题是:
AJAX 响应仅适用于单击的按钮。但我想要两件事

  1. 鼠标悬停时,该用户收藏的评论总数应显示在每个评论的收藏按钮的标题文本中。这样用户就可以轻松地看到我收藏了多少条评论。 (刷新页面后,它可以很好地显示结果。但在 AJAX 响应的帮助下,它应该可以在不重新加载页面的情况下工作)

我想在按钮标题中显示登录用户最喜欢的评论总数,并在单击事件时更新它们。我给出下面的代码,以便您可以轻松理解我想要做什么

输出区号

<?php
$query = mysqli_query($conn, "select * from `comments`");
while ($row = mysqli_fetch_array($query)) {
?>
Comments: <?php echo $row['usercom']; ?><br>
<?php
$query1 = mysqli_query($conn, "select * from `favcoms` where fcom_id='" . $row['cid'] . "' and sessionid='" . $_SESSION['id'] . "'");
$query2 = mysqli_query($conn, "select * from `favcoms` where sessionid='" . $_SESSION['id'] . "'");
?>
<span class="show_like<?php echo $row['cid']; ?>">
<?php if (mysqli_num_rows($query1) > 0) { ?>
<button value="<?php echo $row['cid']; ?>" class="unfavcom"><i title="Remove from Favorite? - (<?php echo mysqli_num_rows($query2); ?>/20)" class="fa fa-star" aria-hidden="true"></i></button>
<?php } else { ?>
<button value="<?php echo $row['cid']; ?>" class="favcom"><i title="Favorite Comment - (<?php echo mysqli_num_rows($query2); ?>/20)" class="fa fa-star-o" aria-hidden="true"></i></button>
<?php } ?>
</span>
<?php
}
?>

这里是 AJAX 部分

$(document).ready(function() {

$(document).on('click', '.favcom', function() {
var id=$(this).val();
$.ajax({
type: "POST",
url: "like.php",
data: {
id: id,
like: 1,
},
success: function() {
showLike(id);
}
});
});

$(document).on('click', '.unfavcom', function() {
var id=$(this).val();
$.ajax({
type: "POST",
url: "like.php",
data: {
id: id,
like: 1,
},
success: function() {
showLike(id);
}
});
});

});

function showLike(id) {
$.ajax({
url: 'show_like.php',
type: 'POST',
async: false,
data:{
id: id,
showlike: 1
},
success: function(response){
$('.show_like'+id).html(response);

}
});
}

这里还有 show_like.php

<?php
session_start();
include('conn.php');

if (isset($_POST['showlike'])) {
$id = $_POST['id'];
$query3=mysqli_query($conn, "select * from `favcoms` where fcom_id='".$id."' and sessionid='".$_SESSION['id']."'");
$query4 = mysqli_query($conn,"select * from `favcoms` where sessionid='".$_SESSION['id']."'");
$numFavs = mysqli_num_rows($query4);
if (mysqli_num_rows($query3) > 0) {
echo '<button class="mycomoptions unfavcom" value="'.$id.'"><font color="#00CC00"><i title="Remove from Favorite? - ('.$numFavs.'/20)" class="fa fa-star" aria-hidden="true"></i></font></button>';
} else {
echo '<button class="mycomoptions favcom" value="'.$id.'"><font color="#00CC00"><i title="Remove from Favorite? - ('.$numFavs.'/20)" class="fa fa-star-o" aria-hidden="true"></i></font></button>' ;
}
}
?>

这里是like.php

<?php
include ('conn.php');
session_start();

if (isset($_POST['like'])) {

$id = $_POST['id'];
$query = mysqli_query($conn,"select * from `favcoms` where fcom_id='$id' and sessionid='".$_SESSION['id']."'") or die(mysqli_error());

if (mysqli_num_rows($query) > 0) {
mysqli_query($conn,"delete from `favcoms` where sessionid='".$_SESSION['id']."' and fcom_id='$id'");
} else {
mysqli_query($conn,"insert into `favcoms` (sessionid,fcom_id) values ('".$_SESSION['id']."', '$id')");
}
}
?>

当用户喜欢任何评论时,每条评论的喜欢评论总数都应该增加,但它只会更新用户喜欢的那一条评论的数字(在 AJAX 响应中)。刷新页面后,每条评论的收藏评论总数显示良好。

单击的按钮类将被更改,或者它应该在每次单击时在空星和彩色星之间切换。因此,字体很棒的星级将仅针对单击的按钮进行更改,但用户最喜爱的评论总数应针对所有评论进行更新。

希望我解释得很好。如果您需要进一步解释,请在评论中询问我。

P.S = 我在配置连接文件中使用 PDO 方法

最佳答案

这将比您要求的要多得多,但这似乎是分享一些我希望有用的知识的好机会。

我很难找到你的“评论总数”代码,因为逻辑和表示应该尽可能分离。所以我尽量不要切换进出 php,除非我要输入值。这导致了一种让服务器返回 JSON 而不是 HTML 的 AJAX 方法。您要求服务器执行一些业务逻辑,然后告诉您结果;不是如何格式化您的页面。

Caveat one: I don't work with mysqli; I use my own data abstraction classes so I don't have to deal with the quirks of PDO vs mysqli vs ODBC etc. So, my code might not show the best use of mysqli.

Caveat two: This is not tested in a browser, so there could be mistakes. This is intended to show concepts, not be copy and paste code.

连接

<?php
/**
* conn.php
*/

// Create connection
$db = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}

初始页面

<?php
require ('conn.php');

// get user's total number of likes
$query = "SELECT COUNT(sessionid) AS total_faves FROM favcoms WHERE sessionid=?";
$result = $db->prepare($query);
$result->bind_param("s", $_SESSION['id']);
$result->execute();

$total = '';
if($row=$result->fetch_object()) {
$total = $row->total_faves;
} else {
// do something on failure
}

// now get all comments with optional sessionid if it has been favorited. coalesce turns null into ''
$query =
"SELECT DISTINCT c.cid, c.usercom, coalesce(f.sessionid, '') " .
"FROM comments AS c " .
"LEFT JOIN favcoms AS f ON c.cid=f.fcom_id AND sessionid=? ";

$comment = $db->prepare($query);
$comment->bind_param("s", $_SESSION['id']);
$comment->execute();

?>

-- 剪断--

HTML 部分:

<input type="hidden" id="total-faves" value="<?= $total ?>" />

<?php while($row = $comment->fetch_object()): ?>

<div id="comment-row-<?= $row->cid ?>" class="commentRow">
Comments: <?= $row->usercom ?>
<button id="button-<?= $row->cid ?>"
val="<?= $row->cid ?>"
class="comment-button <?php $row->sessionid ? 'favcom' : 'unfavcom' ?>">
<i title="Favorite Comment - (<?= $total ?>/20)"
class="fa fa-star<?php $row->sessionid ? '' : '-o' ?>"
aria-hidden="true">
</i>
</button>
</div>

<?php endwhile; ?>

如果评论是最喜欢的,那么图标类将为fa fa-star,否则,它将只是fa fa-star-o。 Javascript 稍后会发挥一些魔力...

现在,由于您对 like.php 的调用有效地切换了收藏夹(在数据库中添加或删除),因此只需使用它来返回结果即可:

like.php

<?php
/**
* like.php
*/

header('Content-Type: application/json'); // <--- Don't miss this!

require ('conn.php');

if (isset($_POST['id'])) {

$id = $_POST['id'];
$query = "select * from `favcoms` where fcom_id=? and sessionid=?";

$stmt = $db->prepare($query);
$stmt->bind_param("s", $id,$_SESSION['id']);
$stmt->execute(); // should check if this succeeds.

// if there is a result, delete it. if not, add it.
if ($stmt->fetch_object()) {
$query = "delete from `favcoms` where fcom_id=? and sessionid=?";
$status = 'not liked';
} else {
$query = "insert into `favcoms` (fcom_id,sessionid) values (?,?)";
$status = 'liked';
}

$stmt = $db->prepare($query);
$stmt->bind_param("s", $id, $_SESSION['id']);
$stmt->execute();

// now find total number of faves and return value
$query = "SELECT COUNT(sessionid) AS total_faves FROM favcoms";
$result = $db->query($query);

$total = '';
if($row = $result->fetch_object()) {
$total = $row->total_faves;
}

echo json_encode(array(
'result' => 'success',
'total' => $total,
'status' => $status
));
} else {

echo json_encode(array(
'result' => 'fail'
));
}

Javascript

$(document).ready(function() {

// dynamically generated buttons must reference a parent element
$(document).on('click', '.comment-button', function() {
var id=$(this).val();
$.ajax({
type: "POST",
url: "like.php",
data: {
id: id,
},
success: function(data) {

var total = data.total;
$('#total-faves').val(total);
toggleButton(id,data);
updateTitles();
}
});
});

// initialize titles here. It could be done in PHP output, but javascript needs to do it later anyway...
updateTitles();


});


function toggleButton(id,data) {

var status = data.status;
var button = $('#button-'+id);
var icon = button.children('i').eq(0);

if(status=='liked') {
button.removeClass('unfavcom').addClass('favcom');
icon.removeClass('fa fa-star-o').addClass('fa fa-star');
} else {
button.removeClass('favcom').addClass('unfavcom');
icon.removeClass('fa fa-star').addClass('fa fa-star-o');
}
}

function updateTitles() {

var total = $('#total-faves').val();
$('.fa fa-star').prop('title',"Favorite Comment - ("+ data.total +"/20)");
$('.fa fa-star-o').prop('title',"Remove from Favorite? - ("+ data.total +"/20)");
}

你的问题的答案就在上面的函数中——但为了达到这个目的,我需要将 AJAX 更改为使用 JSON 而不是 HTML。然后,您可以通过 jquery 看到所有可用的魔力。您需要知道的是哪些行是最喜欢的,并且您可以使用 jquery 设置标题、类等。

--编辑--我只是注意到我没有检查 AJAX 数据是否成功。您始终可以检查它以向用户提供信息。我只是忘记了。

关于javascript - AJAX 响应应更新 while 循环结果中的所有记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47476085/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com