duanrang2627 2013-01-01 12:38
浏览 48

PHP foreach循环中的Ajax POST

I'm using $.post for posting some data, for eg, a variable, company name to a controller method, inside a php foreach loop. In the controller I echo back a bargraph that is plotted using the data that is passed. Now inside the foreach loop I'm dynamically generating an id which will be passed to a certain '' element and I need to plot this bargraph passed back inside that div. The code I'm using now is posted below:

    <?php
        $id=0;
        foreach($customer_companies as $data) {
            $company_name=$data->CompanyName;
            echo '<tr>
                  <script>function show_graph()
            {
                $.post("'.$base.'reports/single_bargraph/'.$company_name.'",      {},function(result){
                       $("#'.$id.'").html(result);
                });
             }                                  
        </script> 
        <td class="tablecntntgry" id="'.$id.'" height="45"> 
            <script type="text/javascript"> show_graph();   </script>                            
        </td>
      </tr>';
?>

Suppose, I have implemented pagination for fetching data $customer_companies, and 3 are displayed in page at a time. Now the problem that I face is the graph is not plotted in the id's specified.:( Sometimes, it would be plotted in the correct 3 td's generated but sometimes 2/3 would be plotted in the same td overlapping the other:( Can someone help me with this?

  • 写回答

3条回答 默认 最新

  • dsfs1233 2013-01-01 12:43
    关注
    1. $id is always zero in your sample.
    2. you need to make separate functions show_graph'.$i.'() (to be honest you don't need functions at all, put your $.post after the table)

    Edit: Your script should looks like this:

    <?php
    
    echo "<table>";
    foreach ($customer_companies as $id => $data) {    
        echo '<tr><td class="tablecntntgry" id="row' . $id . '" height="45"></td></tr>';
    }
    echo "</table>";
    
    // NOTE i open <script> tag after </table> closing tag
    
    echo '<script>';
    foreach ($customer_companies as $id => $data) {
        $company_name = $data->CompanyName;
        echo '
        $.post("' . $base . 'reports/single_bargraph/' . $company_name . '", {},function(result){
            $("#row' . $id . '").html(result);
        });                                  
        ';
    }
    echo '</script>';
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分