- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我绞尽脑汁,但无法得到想要的结果。
在 while 循环中,所有评论都被获取。每个评论都有一个带有 Font Awesome 星号的按钮,可以使该评论成为最爱。我想在鼠标悬停在任何评论的星形按钮上时显示登录用户最喜欢的评论总数。 (这样用户就可以知道到目前为止我收藏了多少条评论。
我正在使用 jQuery AJAX 方法来更新收藏评论的记录。
一切都运行良好,最喜欢的评论正在 mysql 记录中更新,并且 AJAX 响应运行良好。
我的实际问题是:
AJAX 响应仅适用于单击的按钮。但我想要两件事
鼠标悬停时,该用户收藏的评论总数应显示在每个评论的收藏按钮的标题文本中。这样用户就可以轻松地看到我收藏了多少条评论。 (刷新页面后,它可以很好地显示结果。但在 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
的调用有效地切换了收藏夹(在数据库中添加或删除),因此只需使用它来返回结果即可:
<?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'
));
}
$(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/
我正在尝试检查 Entry 中是否存在重复项,并使用内联消息提醒用户该数字存在。 $(document).ready(function(){ $("#con1").blur(function(
我有一个基于类的 View 。我在引导模式上使用 Ajax。为了避免页面刷新,我想使用此类基于 View 返回 JSON 响应而不是 HTTP 响应,但我只看到了如何为基于函数的 View 返回 JS
关闭。这个问题是not reproducible or was caused by typos .它目前不接受答案。 这个问题是由于错别字或无法再重现的问题引起的。虽然类似的问题可能是on-topi
我有一个大型内部企业基于 Web 的应用程序在 IIS6 上运行 ASP.NET 3.5,生成 401 个“未经授权”响应,然后是 200 个“Ok”响应(如 Fiddler 所述)。我知道为什么会发
感谢您研究我的问题。 我有一个node/express服务器,配置了一个server.js文件,它调用urls.js,而urls.js又调用 Controller 来处理http请求,所有这些都配置相
当我使用以下命令时,我得到正确的 JSON 响应: $ curl --data "regno=&dob=&mobile=" https://vitacademics-rel.herokuapp.co
我有一个非常简单的 RESTful 服务,它通过 POST 接收一些表单数据,其目的是在云存储(Amazon S3、Azure Blob 存储等)中简单地保留文本主体(具有唯一 ID)作为一个文件..
UDP 不发送任何 ack,但它会发送任何响应吗? 我已经设置了客户端服务器UDP程序。如果我让客户端向不存在的服务器发送数据,那么客户端会收到任何响应吗? 我的假设是; 客户端 --> 广播服务器地
我有一个电梯项目,其中 有一个扩展 RestHelper 的类,看起来像这样 serve{ "api" / "mystuff" prefix { case a
我们正在寻求覆盖 Kong 错误响应结构并编写自定义消息(即用我们的自定义消息替换“超出 API 速率限制”、“无效的身份验证凭据”等)。 我们要找的错误响应结构(代码是自定义的内部错误代码,与HTT
我正在尝试监听 EKEventStoreChangedNotification 以检查当我的应用程序处于后台时日历是否已更改。 我在 View Controller 的 initWithNibMeth
我了解 javascript,并且正在学习 ASP.NET C# 我想要做什么(完成的是javascript): document.getElementById('divID-1'
是否可以过滤所有 har 对象并仅获取 POST 请求/响应?也许在初始化 BrowserMobProxyServer 期间是这样做的方法?我需要将 har 对象保存到文件中并上传到 har 查看器。
我正在尝试向 Oauth 的 API 发送响应。遗憾的是,Symfony2 文档在解释 $response->headers->set(...); 的所有不同部分方面做得很差。 这是我的 OauthC
我正在尝试测试用例来模拟 api 调用,并使用 python 响应来模拟 api 调用。 下面是我的模拟, with responses.RequestsMock() as rsps: url
在尝试在 Haskell 中进行一些领域驱动设计时,我发现自己遇到了这个问题: data FetchAccessories = FetchAccessories data AccessoriesRes
我正在与 ANT+ USB 棒连接,并用项目 react 器替换我自己天真的“MessageBus”,因为它看起来非常合适。 USB接口(interface)本质上是异步的(单独的输入/输出管道),我
我正在将项目迁移到AFNetworking 2.0。使用AFNetworking 1.0时,我编写了代码来记录控制台中的每个请求/响应。这是代码: -(AFHTTPRequestOperation *
我有以下代码段。 ajaxRequest.onreadystatechange = function(){ if(ajaxRequest.readyState == 4){
我有问题......我在 php 中有一个监听器脚本可以执行以下操作: if ($count != 1) {echo 'no';} else { echo "yes";} 因此它会回显"is"或“
我是一名优秀的程序员,十分优秀!