Passing a PHP variable into a Javascript function

时间:2015-06-25 18:37:56

标签: javascript php jquery

I have a PHP variable that I am declaring upon loading the page, and want to use it in a JavaScript/jQuery function that loads upon a button click.

I have the following on my index.php page:

// Creating a random name for a file and creating it. Working properly.
$fname = substr(md5(rand()), 0, 7);
$file = fopen("temp/" .$fname, 'w');

And when I click a button, the following JavaScript function should run:

//Use the generated filename in the JavaScript function
var fname = <?php echo $fname; ?>;
var fileName = "temp/" + fname;

My understanding is that the PHP variable is outside of the scope of the JavaScript function, since I believe this is the way it should be done.

Can you please help with this?

4 个答案:

答案 0 :(得分:3)

PHP generates a page and presents it to a browser. As far as the browser is concerned, by the time the page is received, PHP is finished. So to answer your question, that should work, since PHP will essentially just spit out the text on to the page, which will act as normal. That is, unless I am terribly misinformed. The "scope" of a PHP variable is long gone by the time Javascript gets to run, so that isn't really an issue.

答案 1 :(得分:1)

Try do this. in a php file of course. var fname = '<?php echo $fname; ?>';

答案 2 :(得分:1)

I think you need an extension on your filename: $extension = ".txt"; $fname = substr(md5(rand()), 0, 7).$extension; $file = fopen("temp/" .$fname, 'w');

答案 3 :(得分:1)

问题是像anant kumar singh所提到的缺失的叛逆者。 我在网页上测试了以下代码:

<?php
        $fname = substr(md5(rand()), 0, 7);
        $file = fopen("temp/" .$fname, 'w');
    ?>
    <html>
    <head
    </head>
    <body>
    <script>
        var fname = "<?php echo $fname; ?>";
        var fileName = "temp/" + fname;
    </script>
    </body>
</html>