简体   繁体   中英

Execute Javascript through PHP

I'm using this PHP code to write a HTML table, but it takes time to load. I was thinking it would be a good idea to let JavaScript do the job, but the problem is that $width and $height are dynamic and is defined on the server-side. How do I get around that?

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>';

I'm unsure if this is best practice, but you can echo from PHP directly into Javascript. For example:

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

Put PHP variables in javascript

<script>

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

</script>

If no paramount forms are intented to exist in your page, you can store them in hidden HTML tags as hidden inputs, like this:

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>";

And then in Javascript get those variables and iterate with them.

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

And so with the width.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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