admin管理员组文章数量:1427496
I am searching for a better way to send my PHP variable to Javascript. Currently I echo the variable in PHP:
<script>
var numbers = <?php echo $numbers ?>;
</script>
I then access this variable in Javascript like this: class.method(numbers);
My PHP file is included in the index.php before the javascript file, so I have access to this variable in the javascript file.
Now I am looking for a nicer way to submit the PHP variable than using echo
. Does anyone have an idea?
The output of numbers looks like:
I am searching for a better way to send my PHP variable to Javascript. Currently I echo the variable in PHP:
<script>
var numbers = <?php echo $numbers ?>;
</script>
I then access this variable in Javascript like this: class.method(numbers);
My PHP file is included in the index.php before the javascript file, so I have access to this variable in the javascript file.
Now I am looking for a nicer way to submit the PHP variable than using echo
. Does anyone have an idea?
The output of numbers looks like:
Share Improve this question edited Feb 27, 2021 at 10:40 sbgib 5,8483 gold badges21 silver badges26 bronze badges asked Jan 15, 2021 at 9:38 Christian TeubnerChristian Teubner 111 silver badge3 bronze badges 6- Actually, you should not mix JS and PHP at all. If you need data on a page, fetch it with AJAX, or include it in a script tag with an appropriate type attribute. – Teemu Commented Jan 15, 2021 at 9:41
- Maybe a hidden field where the value is the php variable and then you may retrieve the field value with javascript – cwhisperer Commented Jan 15, 2021 at 9:48
- @Rory McCrossan How can I attach data to HTML in the smartest way, because in my opinion I have to do it also with echo, because HTML does not know the PHP variables. – Christian Teubner Commented Jan 15, 2021 at 9:49
- 1 @Teemu I agree with you pletely. I removed my ments as they could be misconstrued. – Rory McCrossan Commented Jan 15, 2021 at 9:56
-
1
@RoryMcCrossan Though manipulating JS with PHP is a very monly used practice (
本文标签: How to give PHP variable to JavascriptStack Overflow
版权声明:本文标题:How to give PHP variable to Javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745501216a2661039.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论