php
  • ajax
  • 2016-02-12 155 views 3 likes 
    3

    美好的一天。Php Ajax foreach循环故障

    我正在使用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> &nbsp; &nbsp;<img src='../images/poll_green.jpg' width="+width+" height=20 border=10/> &nbsp;"+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的链接如此:

    你最喜欢哪个电脑品牌? A)。 B)戴尔 C)宏基。 D)三星

    和10人已经投了惠普,4戴尔,7为宏碁和15为三星。

    它应该显示每个计算机品牌的投票数和百分比的标题,这意味着将显示4条记录,但相反,它只显示戴尔的投票数和百分比,如果阿贾克斯但如果只使用PHP,它会显示所有计算机品牌的投票数和百分比正常

    请问,这可能是什么原因以及可能的解决方案?

    感谢

    +0

    如果你的foreach循环运行,更多的则onces,它将覆盖以前的结果。我仍然不明白你遇到的主要问题是什么。 – Ibu

    回答

    0

    我想你是不是添加值,你的反应阵列这里

    $responses_array[] = $response; 
    

    我会尝试增加索引。

    for($j=1;$j<=$count_response;$j++) 
        { 
         $fetch = fetch($poll_response); 
         $response = $fetch['response']; 
         $responses_array[j] = $response; 
        } 
    
    0

    试试这个

    $responses_array[j] = $fetch['response']; 
    

    ,而不是它

    $response = $fetch['response']; 
    $responses_array[] = $response; 
    
    +0

    它没有工作。 – dlastofmykind

    相关问题