最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Inserting PHP variable value in Javascript file - Stack Overflow

programmeradmin1浏览0评论

I have a JavaScript file which has a hard coded BASEURL variable, this value is then used by other functions in the file. I would like for this url value to be set dynamically so that I don't need to manually change it for different installs. Is it possible to insert a PHP variable value into a JavaScript file?

I have a JavaScript file which has a hard coded BASEURL variable, this value is then used by other functions in the file. I would like for this url value to be set dynamically so that I don't need to manually change it for different installs. Is it possible to insert a PHP variable value into a JavaScript file?

Share Improve this question asked Jan 17, 2012 at 11:12 Cronin O'MCronin O'M 6921 gold badge12 silver badges19 bronze badges 0
Add a ment  | 

5 Answers 5

Reset to default 5

Rather than try to mix PHP into javascript files, here's what I do in the HTML template:

<head>
    <script>
        var BASEURL = "<?php echo base_url(); ?>";
    </script>
    <script src="/path/to/my_script1.js"></script>
    <script src="/path/to/my_script2.js"></script>
</head>

This sets the variable and allows all your embedded scripts to access it. base_url() would be replaced by whatever method you use to fetch the base url with PHP.

Suppose you have a JS file written on the fly by PHP; file1.php

<?php
  header('Content-Type: application/javascript');
  $var = $_GET['var1'];
  echo "jsvar = ".$var.";";
?>

The client-side source code of file1.php?var1=10 will then be

jsvar=10;

There exists several ways:

  1. Load the baseurl via AJAX, but maybe this is to slow, maybe you need it earlier.

  2. let the javascript file running through the php parser. Then you could use inline echos.

  3. The most convenient and easiest way, is to make a <script>var baseurl = '...';</script> in the html/php output of your page.

You will need to make your file a php file, not a js file. From there you can include any PHP tags in the file to work your dynamic magic. The key to make this whole thing work is in the headers, which you will need to set like so:

<?php
    Header("content-type: application/x-javascript");
      echo 'var js_var = ' . $php_var;
?>
alert (js_var);

This technique can be used to for CSS files as well.

Heredoc worked for me today:

<?php
echo <<<ANYNAME

<script LANGUAGE="JavaScript" type="text/javascript">
<!--
// code ...
var myLatlng = new google.maps.LatLng($lat, $lon);
// code cont. ...
//-->
</script>

ANYNAME;
?>

http://php/manual/en/language.types.string.php#language.types.string.syntax.heredoc

php variable in html no other way then: <?php echo $var; ?>

发布评论

评论列表(0)

  1. 暂无评论