简体   繁体   中英

Sending $_POST variables to JavaScript

I'm making a simple drawing tool with JavaScript and I'm using PHP to generate a table which is used as a canvas. To enable customizing the dimensions I did this

$input = $_SERVER['REQUEST_METHOD'];

if ($input == 'POST') {
    $width = (int) $_POST['width'];
    $height = (int) $_POST['height'];
}

But I also need to use these same values in JavaScript for creating a String that holds all coordinates for all colored table elements. Is there any way to achieve this?

EDIT: Here is the JS function that needs the values.

        function constructCanvasString(){       

            var width = 128;
            var height = 64:

            var canvasString = width + ' ' + height + '\\n';
            for (var y = 0; y < height; y++) {
                for (var x = 0; x < width; x++) {
                    if (   $('#' + x + '-' + y).css('background-color') !== 'transparent' ) {
                        canvasString = canvasString + x + ' ' + y + ' ' + ($('#' + x + '-' + y).css('background-color')).replace(/\s/g, '') + '\\n';
                    }
                }
            }
            document.getElementById('canvas').value = canvasString;
        }

The function is called when a user clicks a button after the drawing has been drawn (when td elements have gained style attribute background-color)

您可以通过javascript通过以下方式访问PHP变量:

    var width = "<?php echo $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