简体   繁体   English

如何使用 JavaScript 打印 PHP 变量

[英]How I can print PHP variable using JavaScript

I'm trying to print my PHP variable:我正在尝试打印我的 PHP 变量:

<?php
    $section= $_GET['section'];
    $author = $_GET['author'];
?>
<html>
<!--Some HTML page's elements-->
</html>

And my JavaScript code:还有我的 JavaScript 代码:

$(document).ready(function(){
var SECTION = '<?php echo $section;?>';
alert('My section is: ' + SECTION);
var AUTHOR = '<?php echo $author;?>';
alert('Current author is: ' + AUTHOR);
});

But only I get in alert's message: 'My section is: ' + <?php echo $section;?> '但只有我收到警报的消息:'我的部分是:' + <?php echo $section;?> '

Try running this all a single page尝试在一个页面上运行所有这些

test.php?section=5&author=james test.php?section=5&author=james

test.php测试文件

<?php
    $section= $_GET['section'];
    $author = $_GET['author'];
?>
<html>
<!--Some HTML page's elements-->
</html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script>
        $(document).ready(function(){
        var SECTION = '<?php echo $section;?>';
        alert('My section is: ' + SECTION);
        var AUTHOR = '<?php echo $author;?>';
        alert('Current author is: ' + AUTHOR);
        });
</script>

works fine工作正常

The answer provided by Rob will set your JS variables from PHP, but also makes you vulnerable to Javascript injection - Do not use this method as is. Rob 提供的答案将从 PHP 设置您的 JS 变量,但也会使您容易受到 Javascript 注入的影响 -不要按原样使用此方法。

If you want to set JS variables from within PHP, and those variables should be set by the user - simply set them from within JS, or do a very strict input filtering.如果您想从 PHP 内部设置 JS 变量,并且这些变量应该由用户设置 - 只需从 JS 内部设置它们,或者进行非常严格的输入过滤。

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

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