PHP - generating JavaScript

后端 未结 3 891
旧时难觅i
旧时难觅i 2021-02-02 04:30

I am working on a project which has a lot of JavaScript. I think that generating simple strings and putting them between \"

相关标签:
3条回答
  • 2021-02-02 04:36

    You might want to check out json_encode and json_decode.

    0 讨论(0)
  • 2021-02-02 04:46

    I was trying to make my server do an API call and embed it in a html to have javascript process it.. of course put whatever you want in the echo..

    <?php
    // a_local_file.php
    Header("content-type: application/x-javascript");
    
    echo file_get_contents('http://some_remote_script');
    ?>
    

    And use this to refer to it in HTML...

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

    The api call should return valid javascript, otherwise add what you need to make it valid; this is often the troublesomepart with working with json from api calls. Stripslashes, trim, and other string functions may be of use .. but often pesky foreign characters seep in and can set off php errors based on your php setup.

    0 讨论(0)
  • 2021-02-02 04:52

    The best approach is to think Javascript as PHP code.

    The basic steps are:

    1. Create a .htaccess file that redirects all JS files (.js) to a index file.
    2. In this index file load JS file as a PHP module (require "script/$file")
    3. Modify all JS files as you need. Now you can embed PHP code.

    For instance, add to your .htaccess this line:

    RewriteRule \.js$ index.php
    

    In your index.php file put something like this:

    // Process special JS files
    $requested = empty($_SERVER['REQUEST_URI']) ? "" : $_SERVER['REQUEST_URI'];
    $filename = get_filename($requested);
    if (file_ends_with($requested, '.js')) {
         require("www/script/$filename.php");
         exit;
    }
    

    And finally in your file.js.php you can embed PHP, use GET and POST params, etc:

    <?php header("Content-type: application/x-javascript"); ?>
    var url = "<?php echo $url ?>";
    var params = "<?php echo $params ?>";
    
    function xxxx().... 
    ....
    

    In addition, a trick to skip file cache is to add a random number as javascript parameter:

    <script type="text/javascript" src="scripts/file.js?a=<?php echo rand() ?>"></script>
    

    Also, as said in a comment, if your webserver don't allow to modify the .htaccess, you can just ask for the PHP file directly:

    <script type="text/javascript" src="file.php"></script>
    
    0 讨论(0)
提交回复
热议问题