PHP and Javascript error
I am trying to do something like this.
<script type="text/javascript">
$(wi开发者_StackOverflowndow).load(function(){
<?php
if(isset($_SESSION['tagname']))
{
?>
var t = <?php echo $_SESSION['tagname'] ?>;
$('.tag span').html(t);
<?php
}
else
{
?>
$('.tag').hide();
<?php
}
?>
});
</script>
Now the problem is, the variable 't' is not getting set. If I write a static text inside that line of code, then my code works.
Is there anything I am doing wrong here?
If t
is a string value, then that should be a syntax error because you would be using a string outside quotes.
Try
var t = '<?php echo $_SESSION['tagname'] ?>';
Encode as JSON before outputting text to be used as JavaScript literals.
var t = <?php echo json_encode($_SESSION['tagname']) ?>;
And of course, make sure that $_SESSION['tagname']
actually contains something.
Because the t
variable contains a string, which should be enclosed in single or double quotes (in this case, double quotes, as you have single quotes inside the string so it doesn't mess up).
var t = "<?php echo $_SESSION['tagname'] ?>;";
And, it depends if "tagname" is a Javascript variable or not.
精彩评论