javascript 在外部 JS 文件中包含 PHP 变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9653651/
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
Including PHP variables in an external JS file?
提问by Leeloo
I have a few lines of jQuery in my web application. This code is inline at the moment because it accepts a couple of PHP variables.
我的 Web 应用程序中有几行 jQuery。这段代码目前是内联的,因为它接受几个 PHP 变量。
<script type="text/javascript">
$(document).ready(function(){
$('.post<?php echo $post->id; ?>').click(function() {
$.ajax({
type: 'POST',
url: 'http://domain.com/ajax/add_love',
data: {
post_id: <?php echo $post->id; ?>,
user_id: <?php echo $active_user->id; ?>,
<?php echo $token; ?>: '<?php echo $hash; ?>'
},
dataType: 'json',
success: function(response) {
$('.post<?php echo $post->id; ?>').html(response.total_loves).toggleClass('loved');
}
});
return false;
});
});
</script>
I'm a big fan of best practices though, so I would like to move my jQuery into an external JS file.
不过,我是最佳实践的忠实粉丝,所以我想将我的 jQuery 移动到外部 JS 文件中。
How could I achieve such a feat?
我怎么能达到这样的壮举?
Any tips? I'm still relatively new to jQuery and PHP.
有小费吗?我对 jQuery 和 PHP 还是比较陌生。
Thanks!
谢谢!
:)
:)
回答by Tadeck
My solution combines several techniques, some of which are already mentioned within the answers to this question.
我的解决方案结合了多种技术,其中一些技术已在此问题的答案中提及。
Yes, separate PHP from JS
是的,将 PHP 与 JS 分开
First of all: yes, you should separate your JS from PHP. You can put it in a separate file, but you will need to make some changes into your current code. Do not make JS file dynamically generated - it actually kills the advantages of separating JS code into separate file (you cannot cache it etc.).
首先:是的,您应该将您的 JS 与 PHP 分开。您可以将其放在单独的文件中,但您需要对当前代码进行一些更改。不要动态生成 JS 文件——它实际上扼杀了将 JS 代码分离成单独文件的优点(你不能缓存它等)。
Common variables as global variables / function arguments
公共变量作为全局变量/函数参数
Next, store your common variables as global variables in the header of HTML file (you do not really have much choice, although there are other alternatives), preferably grouped in one object:
接下来,将您的公共变量作为全局变量存储在 HTML 文件的标题中(您实际上没有太多选择,尽管还有其他选择),最好分组在一个对象中:
var Globals = <?php echo json_encode(array(
'active_user_id' => $active_user->id,
'token' => $token,
'hash' => $hash,
)); ?>;
Alternatively you can pass all of them as argument(s) to the function you will call, but I assumed you are using them also in other places in your script.
或者,您可以将所有这些作为参数传递给您将调用的函数,但我假设您也在脚本的其他地方使用它们。
Container-dependent data stored in data-
attributes
存储在data-
属性中的容器相关数据
Then use data-
attributes for storing real data associated with containers. You won't need post1
/post2
/post3
-like classes and separate event handlers for them:
然后使用data-
属性来存储与容器相关的真实数据。您将不需要post1
/ post2
/ 之post3
类的类和它们的单独事件处理程序:
<div data-post-id="10">here is something</div>
instead of eg.:
而不是例如:
<div class="post10">here is something</div>
How to read globals and data-
attributes from external JS file
如何data-
从外部 JS 文件中读取全局变量和属性
And then your JavaScript may look like:
然后你的 JavaScript 可能看起来像:
$(document).ready(function(){
$('[data-post-id]').click(function() {
var el = $(this);
var data = {
'post_id': el.data('post-id'),
'user_id': Globals.active_user_id
};
data[Globals.token] = Globals.hash;
$.ajax({
'type': 'POST',
'url': 'http://domain.com/ajax/add_love',
'data': data,
'dataType': 'json',
'success': function(response) {
el.html(response.total_loves).toggleClass('loved');
}
});
return false;
});
});
And this should be sufficient (although I did not test it).
这应该足够了(虽然我没有测试它)。
回答by Corbin
You could always call the function with parameters from PHP:
您始终可以使用 PHP 中的参数调用该函数:
somefile.js:
somefile.js:
function func(params) {
//params is now from PHP
//params.foo == "bar"
}
somefile.php:
somefile.php:
<?php
$params = array('foo' => 'bar');
?>
<script type="text/javascript">
$(function() {
func(<?php echo json_encode($params); ?>);
});
</script>
I tend to go with this approach because it avoids global variables while allowing easily transporting variables.
我倾向于采用这种方法,因为它避免了全局变量,同时允许轻松传输变量。
I like to use json_encode also because anything valid JSON is valid JS meaning you don't have to worry about escaping ' or " if you use a string and echo PHP inside of it.
我喜欢使用 json_encode 也是因为任何有效的 JSON 都是有效的 JS,这意味着您不必担心转义 ' 或 " 如果您使用字符串并在其中回显 PHP。
回答by DanRedux
The way I usually do this is using a few variables in the page itself, then the included JavaScript access those variables.
我通常这样做的方法是在页面本身中使用一些变量,然后包含的 JavaScript 访问这些变量。
In your main page:
在您的主页中:
var post_id=<?php echo $post->id; ?>;
Then in your included JS file:
然后在您包含的 JS 文件中:
data: { post_id: post_id,
回答by devnull69
You cannot put it into an external .js file if you still want to include PHP variables. But you can put the code into a separate PHP file that generates valid Javascript output (including content-type in the header set to "text/javascript"!).
如果您仍想包含 PHP 变量,则不能将其放入外部 .js 文件中。但是您可以将代码放入一个单独的 PHP 文件中,该文件生成有效的 Javascript 输出(包括标题中设置为“text/javascript”的内容类型!)。
In your first PHP file you can refer to the second PHP file generating the Javascript code with
在您的第一个 PHP 文件中,您可以参考生成 Javascript 代码的第二个 PHP 文件
<script src="path/to/generateJS.php" type="text/javascript"></script>
回答by Husain Basrawala
I dont know if a way exists. But if you manage to include variables in external js files, it means that these files will have to be processed as php scripts rendering those variables rather than just rendering them as static files. This will affect performance adversely.
不知道有没有办法。但是,如果您设法在外部 js 文件中包含变量,则意味着必须将这些文件作为呈现这些变量的 php 脚本进行处理,而不仅仅是将它们呈现为静态文件。这将对性能产生不利影响。
One way you can still use external JS file is declaring a function and passing parameters to it from inline javascript. You code would look like:
您仍然可以使用外部 JS 文件的一种方法是声明一个函数并将参数从内联 javascript 传递给它。你的代码看起来像:
<script>
bindPost(<?php echo $post->id; ?>,<?php echo $active_user->id; ?>,'<?php echo $hash; ?>');
</script>
where your bindPost
is declared in external JS file and handles the parameters well.
您bindPost
在外部 JS 文件中声明并很好地处理参数的位置。
回答by Ethan
Without adding a lot more complexity, the easiest way to do this is to have the server treat the Javascript file as a PHP file, so that you can define the PHP variables in that file and then echo them exactly as you're doing in the code in your question.
在不增加更多复杂性的情况下,最简单的方法是让服务器将 Javascript 文件视为 PHP 文件,以便您可以在该文件中定义 PHP 变量,然后完全按照您在你的问题中的代码。
On apache, that means creating a .htaccess file and adding the follwing line to it:
在 apache 上,这意味着创建一个 .htaccess 文件并向其添加以下行:
AddType x-httpd-php .js
(Note that this will process all your javascript files as PHP. If you only want to process some of your Javascript files as PHP you'd need to make a narrower .htaccess rule.)
(请注意,这会将您的所有 javascript 文件作为 PHP 处理。如果您只想将某些 Javascript 文件作为 PHP 处理,则需要制定更窄的 .htaccess 规则。)