简体   繁体   English

当JS需要PHP变量时,如何从PHP中分离javascript?

[英]How can I separate javascript from PHP when the JS needs a PHP variable?

Below is a small snippet from a code I saw with jquery and PHP. 下面是我用jquery和PHP看到的代码中的一小段代码。

Notice the PHP part on line 5, I generally put my javascript into separate files so how would I be able to keep my JS in separate files but still use PHP when needed like below? 注意第5行的PHP部分,我通常把我的javascript放到单独的文件中,这样我怎样才能将我的JS保存在单独的文件中,但是在需要时仍然使用PHP,如下所示?

//when the DOM is ready  
$(document).ready(function(){  
    //settings on top  
    var domain = 'http://davidwalsh.name/';  
    var initialPosts = <?php echo get_posts(0,$_SESSION['posts_start']); ?>;  
    //function that creates posts  
    var postHandler = function(postsJSON) {  
        $.each(postsJSON,function(i,post) {  

What I generally do is : 我通常做的是:

  • put as much JS as possible in a .js file (for caching on the client-side and all that) 尽可能多地将JS放在.js文件中(用于客户端的缓存以及所有这些)
  • this JS code uses a JS variable 这个JS代码使用JS变量
  • that JS variable is declared / initialized from a PHP file ; JS变量是从PHP文件声明/初始化的; this is the only part where you need some code executed on the server-side, actually 实际上,这是您需要在服务器端执行某些代码的唯一部分

For instance, I would have something like this, I suppose : 例如,我想有类似的东西,我想:

my-file.php : my-file.php:

var thisIsMyJSVar = '<?php echo $test; ?>';

So, in PHP, we declare tha variable and set its value. 因此,在PHP中,我们声明变量并设置其值。 This is the "dynamic" part. 这是“动态”部分。

and, in my-file.js : 并且,在my-file.js中:

//when the DOM is ready  
$(document).ready(function(){  
    //settings on top  
    var domain = 'http://davidwalsh.name/';  
    var initialPosts = thisIsMyJSVar;  // Use the JS variable declared in the PHP file
    //function that creates posts  
    var postHandler = function(postsJSON) {  
        $.each(postsJSON,function(i,post) {

Here, in the static JS file, we only use the value ; 在这里,在静态JS文件中,我们只使用该值; nothing here is dynamic, and this file can be cached by the client -- to not be re-downloaded on each page. 这里没有什么是动态的,这个文件可以被客户端缓存 - 不能在每个页面上重新下载。


The problem with that idea is the JS file depends on some initialisation done in the PHP file :-( 这个想法的问题是JS文件依赖于在PHP文件中完成的一些初始化:-(

So, it might be a good idea to have a "default value" in the JS file, just in case... 所以,在JS文件中有一个“默认值”可能是个好主意,以防万一......


Also, you have to have a good namming convention, to not have several files using/declaring/depending on the same JS variable ; 此外,你必须有一个很好的命名约定,没有几个文件使用/声明/取决于相同的JS变量; it might be a good idea, actually, to put all your "configuration variables" inside a single javascript object, to not pollute the global namespace... 实际上,将所有“配置变量”放在一个javascript对象中,不污染全局命名空间可能是一个好主意......

If you want to keep your Javascript separate from your PHP, then use a PHP file to generate a small chunk of Javascript just to set variables. 如果你想让你的Javascript与PHP分开,那么使用PHP文件生成一小部分Javascript来设置变量。 Then use those variables from your .js file: 然后使用.js文件中的那些变量:

HTML: HTML:

<script>
var INITIAL_POSTS = <?php echo get_posts(0,$_SESSION['posts_start']); ?>;
</script>
<script src="my.js">

my.js Javascript file: my.js Javascript文件:

//when the DOM is ready  
$(document).ready(function(){  
    //settings on top  
    var domain = 'http://davidwalsh.name/';  
    var initialPosts = INITIAL_POSTS;  
    //function that creates posts  
    var postHandler = function(postsJSON) {  
        $.each(postsJSON,function(i,post) {

你总是可以让php“写”javascript文件而不是静态 - 没有什么可以阻止<script src="script.php"> ...

There are two basic ways to handle that that don't require mixing JavaScript and PHP at all: 处理它的两种基本方法根本不需要混合使用JavaScript和PHP:

  1. When PHP is generating the page, have it write that output ( get_posts(0,$_SESSION['posts_start']); into a hidden input on the form (or elsewhere on the page). JavaScript can then access this readily 当PHP生成页面时,让它将该输出( get_posts(0,$_SESSION['posts_start']);写入表单上的隐藏输入(或页面上的其他位置)。然后,JavaScript可以轻松访问
  2. Let JavaScript fetch that output from a separate PHP request via AJAX. 让JavaScript通过AJAX从单独的PHP请求中获取该输出。

Generally, if it's the sort of value that won't change while the visitor is browsing the page (or you don't care if it changes, since you won't be updating other content dynamically), write it directly onto the page. 通常,如果它是访问者浏览页面时不会改变的那种值(或者您不关心它是否发生变化,因为您不会动态更新其他内容),请将其直接写入页面。

JavaScript and jQuery can then fetch that value easily with code like 然后,JavaScript和jQuery可以使用类似代码轻松获取该值

var initialPosts = $("#that-hidden-field-mentioned-earlier").val();

Until someone drops in a cleaner answer: 直到某人得到更清晰的回答:

You can define a global js variable in your php/html file, and refer to it in your script: 您可以在php / html文件中定义全局js变量,并在脚本中引用它:

php/html: PHP / HTML:

<script>
var global = <?php echo get_posts(0,$_SESSION['posts_start']); ?>;
</script>

js: JS:

...
var initialPosts = global;
...

This should work, i mean is the file .php? 这应该工作,我的意思是文件.php? As the JS is client side, the php should be processed through the php engine BEFORE the browser processes the client side javascript? 由于JS是客户端,因此在浏览器处理客户端javascript之前,应该通过php引擎处理php?

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

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