2014-01-25 76 views
0

我正在使用此PHP代码编写HTML表格,但加载需要一些时间。我认为让JavaScript执行这项工作是个好主意,但问题是$ width和$ height是动态的,并且是在服务器端定义的。我该如何解决这个问题?通过PHP执行javascript

echo "<table>"; 

    for ($y = 0; $y < $height; $y++) { 
     echo "<tr>"; 
     for ($x = 0; $x < $width; $x++) { 
      echo '<td x="' . $x . ' y="' . $y . ' id="' . $x . '-' . $y . '"></td>';  //coordinates to be used for cropping later 
     } 
     echo '</tr>'; 
    } 
    echo '</table>'; 
+0

如果你知道AJAX,可以调用ajax来调用yr服务器来动态获取宽度和高度,我猜 – lovetostrike

+0

使用AJAX会过度。只需按照@kevinAlbs的建议回显变量即可 – MrVimes

回答

0

认沽PHP变量在JavaScript

<script> 

var height = <?php echo $height ?>; 

</script> 
1

我不确定这是不是最好的做法,但你可以从呼应PHP直接为JavaScript。例如:

<script> 
var width = <?php echo $width; ?>; 
var height = <?php echo $height; ?>; 
//now build table here using the Javascript width and height variables 
</script> 
0

如果没有至高无上的形式intented在你的页面存在,你可以把它们在隐藏的HTML标签存储为隐藏的投入,像这样:

echo ="<form action ='#' name='form'> 
<input type='hidden' name='v_height' id='v_height' value='".$height."'> 
<input type='hidden' name='v_width' id='v_width' value='".$width."'> 
</form>"; 

然后在Javascript中获得这些变量并迭代它们。

jHeight = parseInt(document.form.v_height.value); 

等宽度。