How to define a variable in JavaScript with PHP echo function?

前端 未结 7 1361
囚心锁ツ
囚心锁ツ 2020-12-18 13:33

How do I define a variable in javascript with echo function, from the external php file?

We have theconfigfile.php, thejsfile.js an

相关标签:
7条回答
  • 2020-12-18 14:11

    You can put values in such way only into the files which are processed by PHP.
    External JavaScript-files are not processed by PHP so they are linked as is without sustitution.

    0 讨论(0)
  • 2020-12-18 14:12

    There are a couple of ways you can go about doing this.

    You can configure your webserver to process files with extension .js with PHP and just inject your PHP there. Of course this means you need a way to actually calculate your variable there, and this would slow down serving your regular javascript content.

    You can simply output the PHP variable to a Javascript variable within a <script> element like this

    <script type="text/javascript">
    var path = "<?php echo $path; ?>";
    </script>
    

    And then access this path variable in your AJAX. Most would probably use the second approach.

    0 讨论(0)
  • 2020-12-18 14:17

    In thephpfile.php,

    <html>
    <head>
    <script type="text/javascript">
        var config = { url: '<?= $path; ?>' };
    </script>
    <script type="text/javascript" src="thejsfile.js"></script>
    </head>
    

    Then you can access it with config.url in your javascript.

    0 讨论(0)
  • 2020-12-18 14:20
    echo "<script type='text/javascript'>var AccomodationInfoForm4 =".$path."</script>";
    

    Just try to echo the way shown above and you can access your variable anywhere you want.As this will be available globally to all your js files on your page.

    0 讨论(0)
  • 2020-12-18 14:21

    When working with external JS files You could store the value in a hidden field and retrieve the fields value with JavaScript.

    <input type="hidden" name="path" id="path" value="<?php echo $path; ?>" />
    

    and in the javascript (i'll use jquery)

    var path = $('#path').attr('value');
    

    Obviously you could write the variable to the script tags on the page, but if you use any advanced type of patterns it may be hard to access that variable.

    0 讨论(0)
  • 2020-12-18 14:22

    You can rename your thejsfile.js to thejsfile.php, add the following to the very beginning of it, and it should be parsed for PHP:

    <?php header("Content-type: text/javascript"); ?>
    

    Then reference it like this:

    <head>
    <script type="text/javascript" src="thejsfile.php"></script>
    </head>
    

    Your other option is to just set your server up to parse .js files for PHP.

    0 讨论(0)
提交回复
热议问题