简体   繁体   English

在 javaScript 和 php 之间传输数据

[英]transfer data between javaScript and php

for (let index = 0; index < <? php echo $w_hours?>; index++) {
      table += "<td>" + '<? php $a=0; echo $tab [0]->sch [0] [index] ;>' +"</td>";
}

How to use index here, I have also tried using $a=0 and here global $a and then instead of using index I used $a++ , but still it doesn't increment.如何在这里使用index ,我也尝试过使用$a=0和这里 global $a然后我使用$a++而不是使用index ,但它仍然没有增加。

I think you are trying to render a table using Javascript for the data that is available in PHP script.我认为您正在尝试使用 Javascript 为 PHP 脚本中可用的数据呈现表格。

What you need to do is assign the data from PHP to Javascript and then Javascript will be able to use this data to generate the table.您需要做的是将 PHP 中的数据分配给 Javascript 然后 Javascript 将能够使用此数据生成表格。

If the data is JSON encodable you can have PHP transfer data to a Javascript variable using:如果数据是 JSON 可编码的,您可以使用 PHP 将数据传输到 Javascript 变量:

var dataString = '<?php echo json_encode($tab); ?>';
var tab = JSON.parse(dataString);

var tableRows = '';

tab.forEach((row, index) => {
    //  You can console.log(row) here to check the structure of data in row
    //  and accordingly modify the next line to get desired output
    tableRows = tableRows + '<tr><td>' + row['sch'][0][index] + '</td></tr>';
});

js run on browser and PHP runs on server so obviously, their loop does not have to do anything with each other. Node.js 在浏览器上运行,PHP 在服务器上运行,很明显,它们的循环不必相互做任何事情。

ideally you would get json object from php to js and then js iterate over it.理想情况下,您将从 php 获得 json object 到 js,然后 js 对其进行迭代。

so it should be like this所以应该是这样的

var x = '<?php echo json_encode( $tab[0]->sch[0]);?>';
var w_hours = parseInt('<?php echo $w_hours?>');

Parse it解析它

var rows = JSON.parse(x);  // https://www.w3schools.com/js/js_json_parse.asp

Now you should be able to use for loop on it.现在你应该可以使用 for 循环了。

for (let index = 0; index < w_hours ; index++) {
      table += "<td>" + rows[index] + "</td>";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM