简体   繁体   中英

Echo PHP variable inside jQuery SwitchCase?

I have a jQuery script that I am including on a PHP page that takes mt content and creates facebook/myspace share links. I am having trouble echoing PHP code inside of the swith case statement that builds the share URL's. Here's my code:

case 'facebook': this.href += '?t=' + document.title + '&u=http://foobar.com/detail.php?id='; break;

The server isn't parsing the PHP code correctly, it's passing the value id=<?php echo "1";?> rather than 1. Can I not insert PHP code into a javascript include?

Option 1. In your file.php:

<script type="text/javascript">
   var varName = "<?php echo '1'; ?>"; // global
</script>
<script type="text/javascript" src="myscript.js"></script>

Option 2. create a PHP file that returns the javascript content type externalphp

By default, apache with mod_php doesn't parse files with a .js extension. That behaviour can be modified in the apache config files.

Alternatively (this solution will be less heavy on the parser because it wont parse all .js files), give the javascript files you need to parse a .php extension

Have you tried putting it in a variable instead ?

var varName = '<?php echo "1"; ?>' ; or var varName = "<?php echo '1'; ?>";

and then use that variable in your javascript code.

You may need to use praseInt(...) to get a number through.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM