PHP - generating JavaScript

后端 未结 3 959
旧时难觅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: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:

    
    var url = "";
    var params = "";
    
    function xxxx().... 
    ....
    

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

    
    

    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:

    
    

提交回复
热议问题