简体   繁体   中英

PHP in external .js file syntax issue

I looked around but couldn't find an answer to my current issue.

I want to echo a PHP variable into my external .js file. I then use the PHP variable in a javascript variable and from here use ajax to send the variable/s to my database. I believe I am using incorrect syntax for the php echo. My javascript

content = '<div class="post">' + '<img src="<? echo $pic ?>" />' + '</div>';

Is this possible to echo the PHP variable to the external .js file? Am I using the right syntax in the javascript variable?

Your server will not parse the .js file as PHP. You could name your js file as a .php file, and then use header("Content-type: application/javascript") .

Normally, your httpd is only set to parse files named 'foo.php' for PHP code; name the file foo.php instead of foo.js and manually set the content type:

<?php header('Content-type: application/javascript');?>
content = '<div class="post">' + '<img src="<? echo $pic ?>" />' + '</div>';

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