This question already has an answer here:
这个问题在这里已有答案:
- How to pass variables and data from PHP to JavaScript? 16 answers
- 如何将变量和数据从PHP传递给JavaScript? 16个答案
How do I access PHP variables in JavaScript or jQuery? Do I have to write
如何在JavaScript或jQuery中访问PHP变量?我必须写
<?php echo $variable1 ?>
<?php echo $variable2 ?>
<?php echo $variable3 ?>
...
<?php echo $variablen ?>
I know I can store some variables in cookies, and access these values via cookies, but values in cookies are relatively stable values. Moreover, there is a limit, you can not store many values in cookies, and the method is not that convenient. Is there a better way to do it?
我知道我可以在cookie中存储一些变量,并通过cookie访问这些值,但cookie中的值是相对稳定的值。而且,有一个限制,你不能在cookie中存储很多值,并且方法不那么方便。有没有更好的方法呢?
6 个解决方案
#1
115
Your example shows the most simple way of passing PHP variables to JavaScript. You can also use json_encode for more complex things like arrays:
您的示例显示了将PHP变量传递给JavaScript的最简单方法。您还可以将json_encode用于更复杂的事物,例如数组:
<?php
$simple = 'simple string';
$complex = array('more', 'complex', 'object', array('foo', 'bar'));
?>
<script type="text/javascript">
var simple = '<?php echo $simple; ?>';
var complex = <?php echo json_encode($complex); ?>;
</script>
Other than that, if you really want to "interact" between PHP and JavaScript you should use Ajax.
除此之外,如果你真的想在PHP和JavaScript之间“互动”,你应该使用Ajax。
Using cookies for this is a very unsafe and unreliable way, as they are stored clientside and therefore open for any manipulation or won't even get accepted/saved. Don't use them for this type of interaction. jQuery.ajax is a good start IMHO.
使用cookie是一种非常不安全和不可靠的方式,因为它们存储在客户端,因此可以进行任何操作,甚至不会被接受/保存。不要将它们用于此类交互。 jQuery.ajax是一个很好的开始恕我直言。
#2
5
If AJAX isn't an option you can use nested data structures to simplify.
如果AJAX不是一个选项,您可以使用嵌套数据结构来简化。
<?php
$var = array(
'qwe' => 'asd',
'asd' => array(
1 => 2,
3 => 4,
),
'zxc' => 0,
);
?>
<script>var data = <?php echo json_encode($var); ?>;</script>
#3
2
You're asking kind of a two-part question. As far as syntax (I think since PHP4?) you can use:
你问的是一个由两部分组成的问题。至于语法(我认为自PHP4以来?)你可以使用:
<?=$var?>
... if PHP is configured to allow it. And it is on most servers.
...如果PHP配置为允许它。它在大多数服务器上。
As far as storing user data, you also have the option of storing it in the session:
至于存储用户数据,您还可以选择将其存储在会话中:
$_SESSION['bla'] = "so-and-so";
for persistence from page to page. You could also of course use a database. You can even have PHP store the session variables in the db. It just depends on what you need.
从页面到页面的持久性。您当然也可以使用数据库。你甚至可以让PHP在db中存储会话变量。这取决于你需要什么。
#4
1
Basically, yes. You write alert('<?php echo($phpvariable); ?>');
基本上,是的。你写警报('<?php echo($ phpvariable);?>');
There are sure other ways to interoperate, but none of which i can think of being as simple (or better) as the above.
确实有其他方法可以互操作,但我认为没有一种方法可以像上面那样简单(或更好)。
#5
0
I would say echo() ing them directly into the Javascript source code is the most reliable and downward compatible way. Stay with that unless you have a good reason not to.
我会说echo()将它们直接放到Javascript源代码中是最可靠和向下兼容的方式。除非你有充分的理由不这样做,否则请坚持下去。
#6
0
I ran into a similar issue when building a custom pagination for a site I am working on.
在为我正在处理的网站构建自定义分页时,我遇到了类似的问题。
The global variable I created in functions.php was defined and set to 0. I could output this value in my javascript no problem using the method @Karsten outlined above. The issue was with updating the global variable that I initially set to 0 inside the PHP file.
我在functions.php中创建的全局变量被定义并设置为0.我可以使用上面概述的@Karsten方法在我的javascript中输出这个值没问题。问题是更新我最初在PHP文件中设置为0的全局变量。
Here is my workaround (hacky? I know!) but after struggling for an hour on a tight deadline the following works:
这是我的解决方法(hacky?我知道!)但是在紧迫的截止日期之后挣扎了一个小时后,以下工作:
Inside archive-episodes.php:
在archive-episodes.php里面:
<script>
// We define the variable and update it in a php
// function defined in functions.php
var totalPageCount;
</script>
Inside functions.php
里面的functions.php
<?php
$totalPageCount = WP_Query->max_num_pages; // In my testing scenario this number is 8.
echo '<script>totalPageCount = $totalPageCount;</script>';
?>
To keep it simple, I was outputting the totalPageCount variable in an $ajax.success callback via alert.
为了简单起见,我通过alert在$ ajax.success回调中输出totalPageCount变量。
$.ajax({
url: ajaxurl,
type: 'POST',
data: {"action": "infinite_scroll", "page_no": pageNumber, "posts_per_page": numResults},
beforeSend: function() {
$(".ajaxLoading").show();
},
success: function(data) {
//alert("DONE LOADING EPISODES");
$(".ajaxLoading").hide();
var $container = $("#episode-container");
if(firstRun) {
$container.prepend(data);
initMasonry($container);
ieMasonryFix();
initSearch();
} else {
var $newItems = $(data);
$container.append( $newItems ).isotope( 'appended', $newItems );
}
firstRun = false;
addHoverState();
smartResize();
alert(totalEpiPageCount); // THIS OUTPUTS THE CORRECT PAGE TOTAL
}
Be it as it may, I hope this helps others! If anyone has a "less-hacky" version or best-practise example I'm all ears.
尽管如此,我希望这有助于其他人!如果有人有一个“不那么hacky”的版本或最佳实践的例子我都是耳朵。
#1
115
Your example shows the most simple way of passing PHP variables to JavaScript. You can also use json_encode for more complex things like arrays:
您的示例显示了将PHP变量传递给JavaScript的最简单方法。您还可以将json_encode用于更复杂的事物,例如数组:
<?php
$simple = 'simple string';
$complex = array('more', 'complex', 'object', array('foo', 'bar'));
?>
<script type="text/javascript">
var simple = '<?php echo $simple; ?>';
var complex = <?php echo json_encode($complex); ?>;
</script>
Other than that, if you really want to "interact" between PHP and JavaScript you should use Ajax.
除此之外,如果你真的想在PHP和JavaScript之间“互动”,你应该使用Ajax。
Using cookies for this is a very unsafe and unreliable way, as they are stored clientside and therefore open for any manipulation or won't even get accepted/saved. Don't use them for this type of interaction. jQuery.ajax is a good start IMHO.
使用cookie是一种非常不安全和不可靠的方式,因为它们存储在客户端,因此可以进行任何操作,甚至不会被接受/保存。不要将它们用于此类交互。 jQuery.ajax是一个很好的开始恕我直言。
#2
5
If AJAX isn't an option you can use nested data structures to simplify.
如果AJAX不是一个选项,您可以使用嵌套数据结构来简化。
<?php
$var = array(
'qwe' => 'asd',
'asd' => array(
1 => 2,
3 => 4,
),
'zxc' => 0,
);
?>
<script>var data = <?php echo json_encode($var); ?>;</script>
#3
2
You're asking kind of a two-part question. As far as syntax (I think since PHP4?) you can use:
你问的是一个由两部分组成的问题。至于语法(我认为自PHP4以来?)你可以使用:
<?=$var?>
... if PHP is configured to allow it. And it is on most servers.
...如果PHP配置为允许它。它在大多数服务器上。
As far as storing user data, you also have the option of storing it in the session:
至于存储用户数据,您还可以选择将其存储在会话中:
$_SESSION['bla'] = "so-and-so";
for persistence from page to page. You could also of course use a database. You can even have PHP store the session variables in the db. It just depends on what you need.
从页面到页面的持久性。您当然也可以使用数据库。你甚至可以让PHP在db中存储会话变量。这取决于你需要什么。
#4
1
Basically, yes. You write alert('<?php echo($phpvariable); ?>');
基本上,是的。你写警报('<?php echo($ phpvariable);?>');
There are sure other ways to interoperate, but none of which i can think of being as simple (or better) as the above.
确实有其他方法可以互操作,但我认为没有一种方法可以像上面那样简单(或更好)。
#5
0
I would say echo() ing them directly into the Javascript source code is the most reliable and downward compatible way. Stay with that unless you have a good reason not to.
我会说echo()将它们直接放到Javascript源代码中是最可靠和向下兼容的方式。除非你有充分的理由不这样做,否则请坚持下去。
#6
0
I ran into a similar issue when building a custom pagination for a site I am working on.
在为我正在处理的网站构建自定义分页时,我遇到了类似的问题。
The global variable I created in functions.php was defined and set to 0. I could output this value in my javascript no problem using the method @Karsten outlined above. The issue was with updating the global variable that I initially set to 0 inside the PHP file.
我在functions.php中创建的全局变量被定义并设置为0.我可以使用上面概述的@Karsten方法在我的javascript中输出这个值没问题。问题是更新我最初在PHP文件中设置为0的全局变量。
Here is my workaround (hacky? I know!) but after struggling for an hour on a tight deadline the following works:
这是我的解决方法(hacky?我知道!)但是在紧迫的截止日期之后挣扎了一个小时后,以下工作:
Inside archive-episodes.php:
在archive-episodes.php里面:
<script>
// We define the variable and update it in a php
// function defined in functions.php
var totalPageCount;
</script>
Inside functions.php
里面的functions.php
<?php
$totalPageCount = WP_Query->max_num_pages; // In my testing scenario this number is 8.
echo '<script>totalPageCount = $totalPageCount;</script>';
?>
To keep it simple, I was outputting the totalPageCount variable in an $ajax.success callback via alert.
为了简单起见,我通过alert在$ ajax.success回调中输出totalPageCount变量。
$.ajax({
url: ajaxurl,
type: 'POST',
data: {"action": "infinite_scroll", "page_no": pageNumber, "posts_per_page": numResults},
beforeSend: function() {
$(".ajaxLoading").show();
},
success: function(data) {
//alert("DONE LOADING EPISODES");
$(".ajaxLoading").hide();
var $container = $("#episode-container");
if(firstRun) {
$container.prepend(data);
initMasonry($container);
ieMasonryFix();
initSearch();
} else {
var $newItems = $(data);
$container.append( $newItems ).isotope( 'appended', $newItems );
}
firstRun = false;
addHoverState();
smartResize();
alert(totalEpiPageCount); // THIS OUTPUTS THE CORRECT PAGE TOTAL
}
Be it as it may, I hope this helps others! If anyone has a "less-hacky" version or best-practise example I'm all ears.
尽管如此,我希望这有助于其他人!如果有人有一个“不那么hacky”的版本或最佳实践的例子我都是耳朵。