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条)

报告相同问题?