PHP - JavaScript Generation

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

Are there any more efficient approaches to creating JavaScript objects, functions, calls, etc.? Maybe some conversion classes (from PHP to JavaScript), or maybe there are design patterns that I have to follow?

PS. If that matters, I use MooTools with MochaUI (with MochaPHPControl).

Thanks in advance for your help.

+4
source share
3 answers

A better approach is to think of Javascript as PHP code.

The main steps:

  • Create a .htaccess file that redirects all JS files (.js) to the index file.
  • In this index file, the JS file is loaded as a PHP module ( require "script/$file" )
  • Modify all JS files as needed. You can now embed the PHP code.

For example, add this line to your .htaccess:

 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 the file.js.php file, you can embed PHP, use the GET and POST options, etc.:

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

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

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

Also, as stated in the comment, if your web server does not allow changing .htaccess , you can simply request the PHP file directly:

 <script type="text/javascript" src="file.php"></script> 
+10
source

I tried to get my server to make an API call and embed it in html in order to have a javascript process. 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 link 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 nasty part of working with json from api calls. Strings, truncations, and other string functions can be used .. but often annoying foreign characters leak and can set php errors based on your php setting.

+4
source

You might want to check out json_encode and json_decode .

+2
source

Source: https://habr.com/ru/post/1341771/


All Articles