简体   繁体   English

将PHP变量传递给Javascript函数

[英]Passing a PHP variable into a Javascript function

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. 我有一个PHP变量,要在加载页面时声明,并且想在单击按钮时加载的JavaScript / jQuery函数中使用它。

I have the following on my index.php page: 我的index.php页面上有以下内容:

// 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: 当我单击一个按钮时,以下JavaScript函数应运行:

//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. 我的理解是PHP变量超出了JavaScript函数的范围,因为我认为这是应该这样做的方式。

Can you please help with this? 你能帮忙吗?

PHP generates a page and presents it to a browser. PHP生成页面并将其呈现给浏览器。 As far as the browser is concerned, by the time the page is received, PHP is finished. 就浏览器而言,在收到页面时,PHP已完成。 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. 因此,回答您的问题应该是可行的,因为PHP本质上只会将文本吐出到页面上,这就像正常情况一样。 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. 在运行Javascript之前,PHP变量的“作用域”早已消失,因此这并不是真正的问题。

Try do this. 尝试做这个。 in a php file of course. 在一个PHP文件中。

var fname = '<?php echo $fname; ?>';   

I think you need an extension on your filename: 我认为您需要扩展名:

$extension = ".txt";
$fname = substr(md5(rand()), 0, 7).$extension;
$file = fopen("temp/" .$fname, 'w');

The problem is the missing apostroph like anant kumar singh mentioned. 问题是缺少提到的撇号,就像提到的anant kumar singh。 I tested the following code in a webpage: 我在网页中测试了以下代码:

<?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>

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

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