PHP - generating JavaScript

佐手、 提交于 2019-12-20 09:55:48

问题


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.


回答1:


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>



回答2:


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.




回答3:


You might want to check out json_encode and json_decode.



来源:https://stackoverflow.com/questions/5152055/php-generating-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!