美好的一天。
我正在进行一项民意调查,其中将使用 ajax 显示选票。 举个例子,我有 3 个民意调查:民意调查 1、民意调查 2、民意调查 3。 您必须单击投票 1 的链接以显示投票 1 的结果,其中由于 ajax 而不会重新加载页面。 结果以百分比显示。
这是片段。
$poll_response = query($con, "SELECT *FROM `responses` WHERE `id` = '{$poll_id}'");
$count_response = rows($poll_response);
if($count_response > 0)
{
$responses_array = array();
for($j=1;$j<=$count_response;$j++)
{
$fetch = fetch($poll_response);
$response = $fetch['response'];
$responses_array[] = $response;
}
$responses_values = array_count_values($responses_array);
$min_value = min($responses_values);
foreach($responses_values as $value=>$count_value)
{
?>
<div id='votes'> </div>
<script type="text/javascript">
var percent_num,width,min_val;
var each_count = "<?php echo $count_value;?>";
var total = "<?php echo $count_response;?>";
var response = "<?php echo ucfirst($value);?>";
var min_val = "<?php echo $min_value;?>";
if(each_count > 0)
{
percent_num = ( (each_count *100)/total);
percent_num = Math.round(percent_num);
width = percent_num*2;
}
else
{
width = 1;
percent_num = 0;
}
if(total > 0)
{
var votes = $("#votes");
votes.html("<table width='50%'><tr><td width='25%'>"+response+"</td><td> <img src='../images/poll_green.jpg' width="+width+" height=20 border=10/> "+percent_num+"% </td><td><span class='badge'>"+each_count+"</span></td><br/></tr></table>");
}
else
{
document.write("<div class='alert alert-danger'>No result yet</div>");
}
</script>
<?php
}
?>
上面代码的问题在于它只显示数据库中的一条记录。 举个例子,如果你点击投票 1 的链接,投票 1 会变成这样:
您最喜欢哪个电脑品牌? 一种)。生命值 B)戴尔 C) 宏碁。 D) 三星
10 人投票给惠普,4 人给戴尔,7 人给宏基,15 人给三星。
它应该显示每个计算机品牌的标题及其得票数和百分比,这意味着将显示 4 条记录,但如果使用 ajax,它只会显示 Dell 及其得票数和百分比使用过,但如果只使用PHP,它会正常显示所有电脑品牌以及票数和百分比
请问这可能是什么原因以及可能的解决方案?
谢谢
最佳答案
我认为您没有在此处将值添加到您的响应数组
$responses_array[] = $response;
我会尝试增加索引。
for($j=1;$j<=$count_response;$j++)
{
$fetch = fetch($poll_response);
$response = $fetch['response'];
$responses_array[j] = $response;
}
关于Php Ajax foreach 循环故障,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35354137/