【问题标题】:How can I put an array(that is in php) into the table(js)如何将数组(在 php 中)放入表中(js)
【发布时间】:2020-11-28 08:00:56
【问题描述】:

所以我试图将 php 中的数组放入 js 中的表中。 php连接到服务器,我将它放入一个数组中。数组是:

array(
[0] =>Array([file] => 292929)
[1] =>Array([file] => 1321323)
[2] =>Array([file] => 1232312)
)

所以我正在尝试将上面的数字放入 js 中的表格中。

<script>


var counter = 0;
var max = //gets the total number in array

<?php

$numc = 0

?>
while(parseInt(max) > counter)
{

  var table = document.getElementById("myTable");//Table
  var row = table.insertRow(1);
  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);

  //Variables in cells
  cell1.innerHTML = "Name";
  cell2.innerHTML = '<?php  echo "{$rows[$numc]['file']}";  ?>';

  counter = counter + 1;
  <?php

  $numc = 1 + $numc;

  ?>
}

</script>

我期望的和这张表类似:

Name  292929
Name  1321323
Name  1232312

除了我得到

Name  292929
Name  292929
Name  292929

我知道这是一个范围? php的问题,但我无法将所有php值都放入表中。

【问题讨论】:

    标签: javascript php arrays


    【解决方案1】:

    首先你只用$rows[$numc]['file'] 渲染代码一次 - js 而循环在 php 中是不可访问的

    你可以:

    1. 在 js 中渲染完整的数组:
    <?php
    echo 'const numArray = [' . implode(', ', $rows) . '];';
    ?>
    

    并在 js 中使用它,因为它现在是 js 中的 js 数组 :) (在js中生成numc,在js中递增等等)

    <script>
    
    
    var counter = 0;
    
    <?php
    echo 'const numArray = [' . implode(', ', $rows) . '];';
    ?>
    var max = numArray.length;
    var table = document.getElementById("myTable");//Table
    while(max > counter)
    {
      var row = table.insertRow(1);
      var cell1 = row.insertCell(0);
      var cell2 = row.insertCell(1);
    
      //Variables in cells
      cell1.innerHTML = "Name";
      cell2.innerHTML = numArray[counter];
    
      counter = counter + 1;
    }
    
    </script>
    
    1. 用php制作整个循环,用js渲染,不用while但有重复的部分

    【讨论】:

    • 是的,我在发帖后注意到了这一点。所以我所做的就是将 $rows 放入一个数组中,并使用 json_encode($rows) 将 php 数组放入一个 js 数组中。感谢您的提醒!
    猜你喜欢
    • 2017-05-06
    • 1970-01-01
    • 2021-05-29
    • 2011-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-04
    • 2022-01-15
    相关资源
    最近更新 更多