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