javascript js文件中的PHP变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6170858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 19:45:29  来源:igfitidea点击:

PHP variable inside a js file

phpjavascript

提问by Adam Boostani

Possible Duplicate:
Best way to transfer an array between PHP and Javascript

可能的重复:
在 PHP 和 Javascript 之间传输数组的最佳方式

How do I put the value of a PHP variable inside a Javascript variable? This is what I have now in a js file:

如何将 PHP 变量的值放入 Javascript 变量中?这是我现在在 js 文件中的内容:

test=<?php echo $country; ?>;

回答by rid

Don't forget to properly escape your variables before passing them to JavaScript. Use json_encode()for this, as it escapes and encodes your values in a way suitable for using with JavaScript:

在将变量传递给 JavaScript 之前,不要忘记正确地转义变量。使用json_encode()这个,因为它逃脱,并适用于JavaScript的使用方式编码你的价值观:

test=<?php echo json_encode($country) ?>;

Never simply send the variable un-encoded, as it might break things, or, worse, if the value comes from untrusted sources, compromise your security.

永远不要简单地发送未编码的变量,因为它可能会破坏事物,或者更糟糕的是,如果值来自不受信任的来源,则会危及您的安全。

Also, rename your file to .phpinstead of .jsif you want to be able to insert dynamic PHP code inside it.

此外,如果您希望能够在其中插入动态 PHP 代码,请将您的文件重命名为.php而不是.js

回答by lonesomeday

Remember that the browser doesn't care what the serverside (PHP) code was. It only cares what the rendered code (Javascript and HTML) looks like. So your PHP

请记住,浏览器并不关心服务器端 (PHP) 代码是什么。它只关心呈现的代码(Javascript 和 HTML)是什么样的。所以你的 PHP

test=<?php echo $country; ?>;

will come out something like this, presuming $countryis a string:

会出现这样的结果,假设$country是一个字符串:

test=USA

That is valid Javascript, but it doesn't set testto have the value USA. It sets testto the value of the variable USA, which is almost certainly undefined. You need to use quotation marks to make a Javascript string literal:

这是有效的 Javascript,但它没有设置test为具有值USA。它设置test为变量的值USA,这几乎可以肯定undefined。您需要使用引号来制作 Javascript 字符串文字:

test="<?php echo $country; ?>";

This will be rendered as so:

这将呈现如下:

test="USA";

and will do what you expect.

并且会做你所期望的。



I see now that you've mentioned that the file is a js file. I presumed above that it was a standard PHP-with-HTML file. As it is, everything above is still valid. However, serving a PHP script as Javascript is only slightly tricky.

我现在知道您已经提到该文件是一个 js 文件。我在上面假设它是一个标准的 PHP-with-HTML 文件。事实上,以上所有内容仍然有效。但是,将 PHP 脚本作为 Javascript 提供服务只是有点棘手。

First, name your file filename.php(or whatever other name you want). This is by far the easiest way to get the webserver to know to parse it with PHP. Then use the following instruction to let the browser know that the file is Javascript content:

首先,命名您的文件filename.php(或您想要的任何其他名称)。这是迄今为止让网络服务器知道用 PHP 解析它的最简单方法。然后使用以下指令让浏览器知道该文件是 Javascript 内容:

header('Content-Type', 'text/javascript');

Put that at the very top of your file, before any content is sent to the browser. You can then include PHP variables as you like.

在将任何内容发送到浏览器之前,将其放在文件的最顶部。然后,您可以根据需要包含 PHP 变量。

回答by Saeid Yazdani

put your JS code inside a .php file and try like this:

将你的 JS 代码放在一个 .php 文件中,然后像这样尝试:

<html>

<script language="JavaScript"> 
function echoSession(num) 
{ 
 window.document.newForm.mybox.value=num; 
 <?PHP echo $VAR ?> 
}
 </script>
</html>

The point is your file should be a PHP file to make server to parse it as php. if it is a .js file it will not work

关键是您的文件应该是一个 PHP 文件,以便服务器将其解析为 php。如果它是一个 .js 文件,它将不起作用

回答by bigblind

First of all, to make sure that you understand this, because I see a lot of beginners stumbling over the difference between server side scripting and client side scripting, javascript is a client side scripting language, while PHP is server side. If you understand this, you can basically skip this paragraph. When the user requests a page, such as mysite.com/whatever.php, the request gets sent to the server. Because the user requests the PHP file, the server knows that it should parse the file before sending it to the user. When parsing a file, the server starts n HTML mode, which means that all the text it reads is going directly to the user. From the moment php encounters a or the end of the file. When the end of the file is reached, it sends the output to the user. This output may contain script tags in it's HTML. These peaces of javascript will be executed when they are red together with the HTML by the browser.

首先,为了确保您理解这一点,因为我看到很多初学者在服务器端脚本和客户端脚本之间的区别上磕磕绊绊,javascript 是一种客户端脚本语言,而 PHP 是服务器端。如果你理解了这一点,你基本上可以跳过这一段。当用户请求一个页面时,例如 mysite.com/whatever.php,请求被发送到服务器。因为用户请求的是 PHP 文件,所以服务器知道它应该在将文件发送给用户之前对其进行解析。解析文件时,服务器启动 n HTML 模式,这意味着它读取的所有文本都将直接发送给用户。从 php 遇到文件结尾的那一刻起。当到达文件末尾时,它将输出发送给用户。此输出的 HTML 中可能包含脚本标记。

However, an external javascript file, doesn't need to have the .js extension, just like css. Therefore, you can also make a php file that outputs js, and do as one of the previous answers suggested, so to put this js code in a .php file:

但是,外部 javascript 文件不需要像 css 一样具有 .js 扩展名。因此,您还可以制作一个输出 js 的 php 文件,并按照前面建议的答案之一进行操作,以便将此 js 代码放入 .php 文件中:

var somevar = <?php echo $var; ?>;

as you can see, after the equals sign in the javascript, the php variable $var 's value will be printed. This value will therefore be assigned to the js variable called somevar when the output is red by the browser.

如您所见,在 javascript 中的等号之后,将打印 php 变量 $var 的值。因此,当浏览器输出为红色时,该值将分配给名为 somevar 的 js 变量。

回答by sod

There is the json_encode (http://php.net/manual/de/function.json-encode.php) method to print php variables for javascript.

有 json_encode (http://php.net/manual/de/function.json-encode.php) 方法来打印 javascript 的 php 变量。

test = <?php echo json_encode($value) ?>

Works even if $value is an array, but in your case if it's a string, too.

即使 $value 是一个数组也能工作,但在你的情况下,如果它也是一个字符串。

回答by Gabriel

This is a problem I face often when dealing with js vs php. As my JS applications become more complex there is more and more a desire to keep all my JS in library files and keep my php as clean as possible. One solution I have started using is to do the following:

这是我在处理 js vs php 时经常遇到的问题。随着我的 JS 应用程序变得越来越复杂,越来越多的人希望将我所有的 JS 保存在库文件中,并尽可能保持我的 php 干净。我开始使用的一种解决方案是执行以下操作:

js file:

js文件:

myNamespace.bootstrap = function( payload ){
  ... 
  // internally boot up all the modules that need 
  // the data, passing it where relavent
  module.load( payload );
}

php file:

php文件:

  ...
  <script type="text/javascript">
    myNamespace.bootstrap(<?= json_encode($payload_object); ?>);
  </script>
</body>

This gives you one data injection point for all your scripts with one line of js in your actual php. Should allow you to easy manage data dependencies in your javascript since you can namespace them in php.

这为您的所有脚本提供了一个数据注入点,在您的实际 php 中使用一行 js。应该允许您轻松管理 javascript 中的数据依赖项,因为您可以在 php 中命名它们。

回答by Luke Stevenson

In order for you to be able to use markup within a Javascript file, you must either:

为了能够在 Javascript 文件中使用标记,您必须:

1) Modify your .htaccess file to include *.js as a valid extension for files to be processed through the PHP Engine. (Google around for this)

1) 修改您的 .htaccess 文件以包含 *.js 作为要通过 PHP 引擎处理的文件的有效扩展名。(为此谷歌一下)

2) Change the Javascript file extension from *.js to *.php.

2) 将 Javascript 文件扩展名从 *.js 更改为 *.php。

3) Declare variables which are set through PHP within the main PHP/HTML file, rather than the external Javascript file.

3) 在主 PHP/HTML 文件中声明通过 PHP 设置的变量,而不是外部 Javascript 文件。