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 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛