Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
169
rated 0 times [  175] [ 6]  / answers: 1 / hits: 17640  / 14 Years ago, tue, march 1, 2011, 12:00:00

I am working on a project which has a lot of JavaScript. I think that generating simple strings and putting them between <script> tags is not the best way to do it.



Are there any better approaches to generate JavaScript objects, functions, calls etc? Maybe some convering classes (from PHP to JavaScript) or maybe there are design patterns I should follow?



PS. If it has any relevance - I am using MooTools with MochaUI (with MochaPHPControl).



Thanks in advance for the help.


More From » php

 Answers
20

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>

[#93520] Monday, February 28, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dexter

Total Points: 717
Total Questions: 98
Total Answers: 115

Location: Sudan
Member since Thu, May 7, 2020
4 Years ago
;