How can I add php variable to javascript e.g:
onClick="javas开发者_开发百科cript:alert('echo $name;')Click Me</a>***
but it is not working
i have not includey original becuse it is not showing original …!!
The php looks fine, as long as the $name variable is set. Try this:
onclick="alert('<?php echo $name; ?>');"
Adding PHP variables to javascript can be done simply by using PHP's <?php
and ?>
open/close tags, like so:
<?php $var = 'Hello world!'; ?>
alert('<?php echo $var; ?>');
Alternatively, you can echo javascript code, including any vars. However, this is much less readable, and generally considered bad practice:
<?php $var = 'Hello world!';
echo "alert('$var');"; ?>
Edit: The example code you typed is nearly correct; all that you missed are the PHP opening and closing tags, as I used in my answer above.
Also try this:
onclick="var text = '<?php echo $name; ?>'; alert(text);"
otherwise unterminated string literal" error appear
another way using short php tags and str_replace() function
onclick="alert('<?=str_replace("'", "\'", $name);?>');"
In your php.ini short_open_tag must be enabled or use normal approach using echo
onclick="alert('<? echo str_replace("'", "\'", $name); ?>');"
php.ini code:
short_open_tag = On
精彩评论