将变量从 PHP 传递到 JavaScript 的有效方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10889233/
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
Efficient way to Pass variables from PHP to JavaScript
提问by user606521
From time to time I have to pass some variables from PHP to JS script. For now I did it like this:
有时我必须将一些变量从 PHP 传递到 JS 脚本。现在我是这样做的:
var js-variable = "<?php echo $php-variable; ?>";
But this is very ugly and I can't hide my JS script in .js file because it has to be parsed by PHP. What is the best solution to handle this?
但这非常难看,我无法在 .js 文件中隐藏我的 JS 脚本,因为它必须由 PHP 解析。处理这个问题的最佳解决方案是什么?
回答by ilanco
If you don't want to use PHP to generate your javascript (and don't mind the extra call to your webserver), use AJAX to fetch the data.
如果您不想使用 PHP 来生成您的 javascript(并且不介意额外调用您的网络服务器),请使用 AJAX 来获取数据。
If you do want to use PHP, always encode with json_encode before outputting.
如果您确实想使用 PHP,请在输出前始终使用 json_encode 进行编码。
<script>
var myvar = <?php echo json_encode($myVarValue); ?>;
</script>
回答by biplav
Please use a rest/rpc api and pass json to your js. This can be done in the following way if you are using jquery:
请使用rest/rpc api并将json传递给您的js。如果您使用 jquery,这可以通过以下方式完成:
rest.php
休息.php
<?php echo "{name:biplav}" ?>
Then From your js make a get call like this:
然后从你的 js 进行这样的 get 调用:
var js_var;
$.get("rest.php", function(data) {
js_var=data;
});
Thats the simplest example I can think of.
这是我能想到的最简单的例子。
回答by goat
<?php
// filename: output-json.php
header('content-type:application/json;charset=utf-8');
printf('var foo = %s;', json_encode($foo, JSON_PRETTY_PRINT));
json_encode
is a robust function that ensures the output is encoded and formatted as valid javascript / json. The content-type header tells the browser how to interpret the response.
json_encode
是一个强大的函数,可确保输出被编码和格式化为有效的 javascript / json。content-type 标头告诉浏览器如何解释响应。
If your response is truly JSON, such as:
如果您的响应确实是 JSON,例如:
{"foo": 5}
Then declare it as content-type:application/json;charset=utf-8
. JSON is faster to parse, and has much less chance of being xss exploited when compared to javascript. But, if you need to use real javascript in the response, such as:
然后将其声明为content-type:application/json;charset=utf-8
. 与 javascript 相比,JSON 解析速度更快,并且被 xss 攻击的可能性要小得多。但是,如果您需要在响应中使用真正的 javascript,例如:
var obj = {foo: 5};
Then declare it as content-type:text/javascript;charset=utf-8
然后将其声明为 content-type:text/javascript;charset=utf-8
You can link to it like a file:
您可以像文件一样链接到它:
<script src="output-json.php"></script>
Alternatively, it can be convenient to embed the value directly in your html instead of making a separate http request. Do it like so:
或者,可以方便地将值直接嵌入到您的 html 中,而不是发出单独的 http 请求。这样做:
<script>
<?php printf('var foo = %s;', json_encode($foo, JSON_HEX_TAG | JSON_PRETTY_PRINT)) ?>
</script>
Make sure to use JSON_HEX_TAG
if embedding into your html via the <script> tag, otherwise you risk xss injection attacks. There's also other flags you may need to make use of for more security depending on the context you use it in: JSON_HEX_AMP, JSON_HEX_QUOT, JSON_HEX_APOS
. Those flags make the response less human readable, but are generally good for security and compatibility, so you should probably just use them.
请确保使用JSON_HEX_TAG
if 通过 <script> 标签嵌入到您的 html 中,否则您将面临 xss 注入攻击的风险。根据您在以下情况下使用它的上下文,您可能还需要使用其他标志来提高安全性:JSON_HEX_AMP, JSON_HEX_QUOT, JSON_HEX_APOS
。这些标志使响应的可读性降低,但通常有利于安全性和兼容性,因此您可能应该使用它们。
I really want to emphasize the importance of declaring the content type and possibly using the JSON_HEX_TAG
flag, as they can both help mitigate xss injection.
我真的想强调声明内容类型和可能使用JSON_HEX_TAG
标志的重要性,因为它们都可以帮助减轻 xss 注入。
Do notdo this unless you wish to tempt an xss attack:
难道不,除非你想吸引的XSS攻击做到这一点:
<script>
var myvar = <?php echo json_encode($myVarValue); ?>;
</script>
回答by Francesco Casula
In my opinion, if you need to pass a variable directly in your JS, probably your web application is not good designed.
在我看来,如果你需要直接在你的 JS 中传递一个变量,可能你的 web 应用程序设计得不好。
So, I have two tips:
* Use JSON files for general configurations, like /js/conf/userprefs.json
所以,我有两个技巧: * 使用 JSON 文件进行一般配置,例如 /js/conf/userprefs.json
{
"avatar": "/img/users/123/avatar.jpg",
"preferred_color": "blue"
// ...
}
- or (better way) you can retrieve your json confs with an AJAX call.
- 或者(更好的方法)您可以使用 AJAX 调用检索您的 json confs。
With PHP frameworks like Symfony2, you can decide a format in your routing configuration leaving the output of a variable to the template engine (like Twig).
使用像 Symfony2 这样的 PHP 框架,您可以在路由配置中决定一种格式,将变量的输出留给模板引擎(如 Twig)。
I do an example for Symfony2 users but this can be used by any programmer:
我为 Symfony2 用户做了一个例子,但这可以被任何程序员使用:
routing.yml
路由.yml
userprefs:
pattern: /js/confs/userprefs.{_format}
defaults: { _controller: CoreBundle:JsonPrefs:User, _format: json }
requirements:
_format: json
_method: GET
Inside the controller you can do all the queries that you need to retrieve your variables putting these in the view:
在控制器内部,您可以执行检索变量所需的所有查询,并将这些变量放入视图中:
Resources/Views/JsonPrefs/User.json
资源/视图/JsonPrefs/User.json
{
"avatar": "{{ user.avatar }}",
"preferred_color": "{{ user.preferred_color }}"
// ...
}
Inside your JS now you'll be able to retrieve the JSON with a simple AJAX call. For performance purposes you can cache the JSONs (for example) with Varnish. In this way your server doesn't need to do a query every time you read the user preferences.
现在在您的 JS 中,您将能够通过一个简单的 AJAX 调用来检索 JSON。出于性能目的,您可以使用 Varnish 缓存 JSON(例如)。通过这种方式,您的服务器不需要在您每次读取用户首选项时进行查询。
回答by Eliot Ball
If you modify your .htaccess file to include
如果您修改 .htaccess 文件以包含
AddType application/x-httpd-php .js
you can use a .js file and it will be handled by PHP, which is half of what you require.
您可以使用 .js 文件,它将由 PHP 处理,这是您需要的一半。
In terms of how ugly that solution is, I would say that this is the least ugly mechanism. You could try to pass your whole JS script through a PHP script as a string and do a search and replace for the variables you need to insert, but I think that you will agree that this is uglier than the solution you are currently using.
就该解决方案的丑陋程度而言,我会说这是最不丑陋的机制。您可以尝试将整个 JS 脚本作为字符串通过 PHP 脚本传递,并搜索并替换您需要插入的变量,但我认为您会同意这比您当前使用的解决方案更丑陋。
回答by MaxArt
Put all your .js files in a folder and configure your HTTP server to redirect all the request to those files to a PHP file that loads the files and outputs them.
将所有 .js 文件放在一个文件夹中,并配置您的 HTTP 服务器以将所有对这些文件的请求重定向到一个 PHP 文件,该文件加载文件并输出它们。
Let's suppose you have Apache and your .js files are in /js:
假设您有 Apache 并且您的 .js 文件在 /js 中:
RewriteRule /js /getjs.php
getjs.php:
getjs.php:
<?php
header('Content-Type: text/javascript');
include_once($_SERVER['SCRIPT_NAME']);
?>
回答by wroniasty
As far as avoiding running .js files through the PHP parser, there is little you can do, except maybe fetching the value of js-variable
via an AJAX call.
至于避免通过 PHP 解析器运行 .js 文件,除了可能js-variable
通过 AJAX 调用获取值之外,您无能为力。
Also you may consider outputing the value like this:
您也可以考虑输出这样的值:
var js_variable = <?php echo json_encode ($php_variable); ?>
to escape all the things that would break your javascript.
逃避所有会破坏你的javascript的事情。
回答by Kevin
At the very least, you can use a PHP shortcode to make your "ugly" solution a bit cleaner:
至少,您可以使用 PHP 短代码使您的“丑陋”解决方案更简洁一些:
var js-variable = "<?= $php-variable ?>";