write javascript to page based on a condition
I need to remove some Javascript code based on a server side condition (PHP). What I currently have is a variable holding the Javascript code as text and based on the condition I either echo it or not. However, it's cumbersome to maintain. How do I go about doing it?
I also tried to开发者_如何学JAVA use something like what follows, but it's not working.
<?php if(condition) { ?> <script> stuff here </script> <?php } ?>
I'm sorry for the formatting, I have no idea why the less-then sign is making the entire line disappear.
The best way is to do something like this:
<?php
if ($something) {
?>
<script>
alert('hi')
</script>
<?php
}
?>
Besides including it in a variable and outputting it conditionally, the only other possibility that I can think of is to put the JavaScript code in a file, and then have a PHP condition which outputs an include for that JavaScript file if it is true.
This doesn't work?
<?php if(condition){ ?>
<script> ... </script>
<?php } ?>
<?php
define('condition', true);
if(condition) { ?> <script> stuff here </script> <?php } ?>
should work
what about hiding or showing the // comment lines with php?
if ($something){
echo "//"; ?> <script>
<?php
echo "//"; ?> alert('hi')
<?php
echo "//"; ?> </script>
<?php
}
精彩评论