我想用jQuery和Ajax製作一個類似/不同的按鈕。問題在於,當我喜歡某些東西時,我無法像它一樣刷新頁面,如果我不喜歡它,在刷新頁面之前我不會再喜歡它。點擊jQuery和AJAX只能工作一次
這裏是我的PHP/HTML:
<?php
require('con.php');
session_start();
if (!empty($_POST)) {
$un = $_SESSION['un'];
$op = $_POST['op'];
$pid = $_POST['pid'];
if ($op == "like") {
mysqli_query($con, "INSERT INTO likes (pid, uid, date_liked, username) VALUES ('$pid', '".$_SESSION['id']."', now(), '".$_SESSION['un']."')") or die(mysqli_error($con));
echo 1;
exit;
} elseif ($op == "unlike") {
mysqli_query($con, "DELETE FROM likes WHERE pid = '$pid' AND username = '$un'");
echo 1;
exit();
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Test 2 Test</title>
<script src="//code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<?
$sql = mysqli_query($con, "SELECT * FROM posts") or die(mysqli_error($con));
//get all the posts from the posts table
while ($r = mysqli_fetch_assoc($sql)) {
$b = $r['body'];
$u = $r['uid'];
$pid = $r['pid'];
$s = mysqli_query($con,"SELECT username, pid FROM likes WHERE pid = '$pid' ") or die(mysqli_error($con));
//get all the likes that correspond with the post id from the likes table
$n = mysqli_num_rows($s);
//the number of likes
$r = mysqli_fetch_assoc($s);
$user = $r['username'];
if ($user !== $_SESSION['un']) {
//if the user hasn't liked the post yet
echo "<div>$b</div>";
echo "<input type = 'button' value = '$n' id = 'like_$pid' class='$pid'>";
//the like button
echo "<br><br>"; ?>
<!-- jQuery Script here -->
<?
} else {
//the user has liked the post
echo "<div>$b</div>";
echo "<input type = 'button' value = '$n' id = 'unlike_$pid' class='$pid'>";
//the unlike button
echo "<br><br>"; ?>
<!-- More jQuery -->
<?
}
}
?>
我的jQuery:
$(document).ready(function() {
$('#like_' + <? echo $pid; ?>).click(function() {
var val = parseInt($(this).val(), 10);
var pid = $("." + <? echo $pid; ?>).val();
//create a variable with the num of likes
$.post("test2test.php", {op: "like", pid: pid}, function(data) {
val = val + 1;
$('#like_' + <? echo $pid; ?>).val(val);
$("#like_" + <? echo $pid; ?>).attr("id", "unlike_<? echo $pid; ?>");
});
});
$('#unlike_' + <? echo $pid; ?>).click(function() {
var val = parseInt($(this).val(), 10);
var pid = $("." + <? echo $pid; ?>).val();
$.post("test2test.php", {op: "unlike", pid: pid}, function(data) {
val = val - 1;
$("#unlike_" + <? echo $pid; ?>).val(val);
$('#unlike_' + <? echo $pid; ?>).attr("id", "like_<? echo $pid; ?>");
});
});
});
我把這段代碼無論它說<!--jQuery Script here-->
或<!--More jQuery-->
所有這一切都是在一個頁面上。我沒有收到任何PHP的JavaScript錯誤,所以我不知道發生了什麼。
請幫幫我。
PS:我是jQuery的初學者,所以請不要讓你的回答太複雜。
謝謝。
現在它喜歡每個帖子和不喜歡的每一篇文章 – nitrous
改變它''[id^= different_ <?echo $ pid;?>]' – nitrous