gpt4 book ai didi

php - 如何使用 Jquery Ajax 更新 PHP 变量?

转载 作者:行者123 更新时间:2023-11-29 06:15:47 26 4
gpt4 key购买 nike

我正在创建一个简单的选民,可以投“喜欢”票或“不喜欢”票。然后,我统计喜欢和不喜欢的总数并输出总数。我想出了如何使用 Jquery Ajax 进行投票,但是投票后票数没有更新。我想使用 Jquery Ajax 更新 $numlike$numdislike 变量。

这是与输出相关的 PHP 脚本:

$like = mysql_query("SELECT * FROM voter WHERE likes = 1 ");
$numlike = 0;
while($row = mysql_fetch_assoc($like)){
$numlike++;
}

$dislike = mysql_query("SELECT * FROM voter WHERE likes = 0 ");
$numdislike = 0;
while($row = mysql_fetch_assoc($dislike)){
$numdislike++;
}

echo "$numlike like";
echo "<br>";
echo "$numdislike dislike";

更新:Jquery Ajax 用于上传投票

<script>
$(document).ready(function(){
$("#voter").submit(function() {

var like = $('#like').attr('value');
var dislike = $('#dislike').attr('value');

$.ajax({
type: "POST",
url: "vote.php",
data: "like=" + like +"& dislike="+ dislike,
success: submitFinished
});

function submitFinished( response ) {
response = $.trim( response );

if ( response == "success" ) {
jAlert("Thanks for voting!", "Thank you!");
}

return false;
});
});
</script>

<form id="voter" method="post">
<input type='image' name='like' id='like' value='like' src='like.png'/>
<input type='image' name='dislike' id='dislike' value='dislike' src='dislike.png'/>
</form>

投票.php:

if ($_POST['like'])
{
$likeqry = "INSERT INTO test VALUES('','1')";
mysql_query($likeqry) or die(mysql_error());
echo "success";
}

if ($_POST['dislike'])
{
$dislikeqry = "INSERT INTO test VALUES('','0')";
mysql_query($dislikeqry) or die(mysql_error());
echo "success";
}

最佳答案

如果您想在单击后更改当前喜欢或不喜欢的号码,您必须返回结果而不是打印它!返回 json 结果并回显此结果并更改 div insideHTML 以查看新结果!

............
............
............
$dislike = mysql_query("SELECT * FROM voter WHERE likes = 0 ");
$numdislike = 0;
while($row = mysql_fetch_assoc($dislike)){
$numdislike++;
}

echo json_encode( array( $numlike, $numdislike ) ) ;
exit();

现在在您的 html 代码中:

       $.ajax({
type: "POST",
url: "vote.php",
context:$(this)
data: "like=" + like +"& dislike="+ dislike,
success: submitFinished(data)
});

function submitFinished( response ) {
response = $.parseJSON( response );
//Now change number of like and dilike but i don't know where are shown in your html
$('#like').attr('value',response[0]);
$('#dislike').attr('value',response[1]);
return false;
});

关于php - 如何使用 Jquery Ajax 更新 PHP 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6633842/

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