dongxian8272 2019-07-10 00:01
浏览 220
已采纳

如何在javascript中插入带有innerHTML的php数组

I would like to be able to insert html code from javascript, which inserts php code that contains an array. What I do is get in the variable $ teams an array of teams. And then I go through the array with a foreach to set the values ​​in the select options

I have done the following but it does not work.

document.getElementById('selectTeam').innerHTML = '<select class="form-control"><?php $teams = ControllerTeam::ctrTeam(); foreach ($teams as $key => $value) { echo '<option value="'.$value["id"].'">'.$value["name"].'</option>';}?></select>';
  • 写回答

2条回答 默认 最新

  • douershuang7356 2019-07-10 00:36
    关注

    First problem is that, probably, the content is loaded after the JS so the selector returns null hence the error in the OP code. Cannot set property 'innerHTML' of null

    That means, you should only execute the JS code on window.load or any other similar event that ensures the fact that the HTML is loaded before trying to execute.

    Now, for the other issue in the comments, if you rewrite the PHP code like this :

    <?php
    $teams = ControllerTeam::ctrTeam();
    
    $options_html = '';
    foreach ($teams as $key => $value) { 
        $options_html .= '<option value="' . $value["id"] . '">' . $value["name"] . '</option>';
    }?>
    

    And in the JS - make sure it loads on window.load or similar -

    document.getElementById('selectTeam').innerHTML = 
        '<select class="form-control"><?php echo $options_html ?></select>';
    

    This makes the code more readable and helps you debug easier.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何能达到用ping0.cc检测成这样?如图
  • ¥15 关于#DMA固件#的问题,请各位专家解答!
  • ¥15 matlab生成的x1图不趋于稳定,之后的图像是稳定的水平线
  • ¥15 请问华为OD岗位的内部职业发展通道都有哪些,以及各个级别晋升的要求
  • ¥20 微信小程序 canvas 问题
  • ¥15 系统 24h2 专业工作站版,浏览文件夹的图库,视频,图片之类的怎样删除?
  • ¥15 怎么把512还原为520格式
  • ¥15 MATLAB的动态模态分解出现错误,以CFX非定常模拟结果为快照
  • ¥15 求高通平台Softsim调试经验
  • ¥15 canal如何实现将mysql多张表(月表)采集入库到目标表中(一张表)?