dongxian8272
2019-07-10 00:01
浏览 181

如何在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>';

图片转代码服务由CSDN问答提供 功能建议

我希望能够从javascript中插入html代码,它会插入包含数组的php代码。 我所做的是让变量$ teams进入一系列团队。 然后我用foreach遍历数组以在选择选项中设置值

我已完成以下操作但它不起作用。

  document.getElementById('selectTeam')。innerHTML ='&lt; select class =“form-control”&gt;&lt;?php $ teams = ControllerTeam :: ctrTeam();  foreach($ teams as $ key =&gt; $ value){echo'&lt; option value =“'。$ value [”id“]。'”&gt;'。$ value [“name”]。'&lt; / 选项&gt;';}?&gt;&lt; / select&gt;'; 
   
 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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.

    已采纳该答案
    打赏 评论
  • dream2891 2019-07-10 00:05

    There is a typo in your code. Please change it to:

    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>';
    
    打赏 评论

相关推荐 更多相似问题