简体   繁体   English

如何生成Javascript和PHP,并将其放入.js文件

[英]how can i generate Javascript and with PHP and put it into a .js file

I want to generate javascript dinamically with php, but i want the code to appear in a different file, and call it from my index file in order to have a better structured code. 我想用php动态生成javascript,但我希望代码出现在不同的文件中,并从索引文件中调用它,以便获得更好的结构化代码。

Do you know a good way to do so? 您知道这样做的好方法吗?

I don't think it's good idea. 我不认为这是个好主意。 It's better to put static JS code into file and pass only needed variables from PHP to HTML (not to JS file). 最好将静态JS代码放入文件中,然后仅将所需的变量从PHP传递到HTML(而不是JS文件)。

But if you want to do it, you can use, eg. 但是,如果您想这样做,可以使用例如。 file_put_contents() to write to file. file_put_contents()写入文件。 Or any other function that can do that (there are many ways). 或可以执行此操作的任何其他函数(有很多方法)。

Also you can consider using .htaccess to change, eg. 您也可以考虑使用.htaccess进行更改,例如。 scripts.php to script.js and generate JS code from it without saving each time to file. scripts.phpscript.js并从中生成JS代码,而无需每次都保存到文件中。

You can name a file anything you want as long as the file name ends with .php (or whatever extension is run by PHP). 您可以为文件命名,只要文件名以.php (或由PHP运行的任何扩展名)即可。

In the past I have used a file name like script.js.php so that I know it's JavaScript built by PHP. 过去我曾使用过诸如script.js.php之类的文件名,所以我知道它是PHP所构建的JavaScript。

At the beginning of the file make sure you change the mime type. 在文件的开头,请确保您更改了mime类型。 This has to be at the very beginning of the file with no white space before it. 它必须在文件的开头,并且之前没有空格。

<?php header("Content-type: text/javascript"); ?>

In your index file you would reference it like common JavaScript. 在索引文件中,您将像普通JavaScript一样引用它。

<script src="script.js.php"></script>

After your header you would have code like this: 标头之后,您将具有以下代码:

var data = <?php echo json_encode($data); ?>;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM