在过去的两天里,我一直在努力让这个工作没有运气。它执行一次,但在初始加载后无法继续更新。该功能不会自动更新,也不会在 30 秒后重新启动。该代码对我来说似乎很好,但显然我对长轮询存在一些知识差距,这导致它不起作用。如果有人有时间,如果您能梳理一下并告诉我我做错了什么,我将不胜感激。任何帮助表示赞赏,谢谢。
JavaScript/jQuery
function poll(pid){
var dataString = 'pid=' + pid;
$.ajax({type: 'GET', url: 'http://localhost:8888/mysite/execs/vote_count.php', data: dataString, async: true, cache: false, success: function(data){
var post = $('#' +pid);
var post_children = post.children();
var upvotes = post_children.find('.upvotes');
var downvotes = post_children.find('.downvotes');
downvotes.text("-" + data.downvotes);
upvotes.text("+" + data.upvotes);
}, dataType: "json", complete: poll, timeout: 30000 });
};
$(".post").each(function(){
poll($(this).attr("id"));
});
PHP (vote_count.php)
<?php
$hostname = 'localhost';
$username = 'root';
$password = 'root';
$database = 'database';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("SELECT * FROM vote WHERE post = :pid AND rating = 'votedown'");
$pid = $_GET['pid'];
$stmt->bindParam(':pid', $pid, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetchAll();
}
catch(PDOException $e)
{
echo $e->getMessage();
}
$stmt->execute();
$downvotes = $stmt->rowCount();
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("SELECT * FROM vote WHERE post = :pid AND rating = 'voteup'");
$pid = $_GET['pid'];
$stmt->bindParam(':pid', $pid, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetchAll();
}
catch(PDOException $e)
{
echo $e->getMessage();
}
$stmt->execute();
$upvotes = $stmt->rowCount();
$arr = array("downvotes"=>$downvotes,"upvotes"=>$upvotes);
echo json_encode($arr);
$dbh = null;
?>