在 JQuery 中使用 PHP 变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10668311/
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-08-24 22:46:14  来源:igfitidea点击:

Use a PHP variable in JQuery

phpjquery

提问by Aaron Fisher

Is there anyway I can use a php variable in the JQuery script?

无论如何我可以在 JQuery 脚本中使用 php 变量吗?

Example:

例子:

  • PHP variable: $sr2
  • Excerpt of JQuery script (with variable): $('#a2_bottom_$sr2')
  • PHP变量: $sr2
  • JQuery 脚本摘录(带变量): $('#a2_bottom_$sr2')

How can I make it so the variable is valid in that JQuery part?

我如何才能使该变量在该 JQuery 部分中有效?

Thanks

谢谢

采纳答案by Lix

What you could simply do is use your PHP to echo out the code to initiate a JavaScript variable.

您可以简单地做的是使用您的 PHP 回显代码以启动 JavaScript 变量。

<script type="text/javascript">
<?php

  $phpVar = "foo";
  echo "var phpVariable = '{$phpVar}';";

?>
</script>

Once the PHP code is parsed, and the HTML is sent to the user - all they will see is the result of the PHP echo -

一旦解析了 PHP 代码,并将 HTML 发送给用户 - 他们将看到的只是 PHP 回显的结果 -

<script type="text/javascript">
  var phpVariable = 'foo';
</script>

Now your phpVariableis available to your JavaScript! So you use it like you would in any other case -

现在您phpVariable的 JavaScript 可以使用了!所以你可以像在任何其他情况下一样使用它 -

$("div."+phpVariable);

That will retrieve us any <div>element with a fooclass -

这将检索我们任何<div>具有foo类的元素-

<div class="foo"></div>

回答by Marc B

PHP runs on the server, jquery runs on the client. If you want a PHP variable to be available to jquery (and by extension, the underlying javascript engine), you'll have to either send the variable's value over at the time you output the page on the server, e.g.

PHP runs on the server, jquery runs on the client. If you want a PHP variable to be available to jquery (and by extension, the underlying javascript engine), you'll have to either send the variable's value over at the time you output the page on the server, e.g.

<script type="text/javascript">
    var my_php_var = <?php echo json_encode($the_php_var) ?>;
</script>

or retrieve the value via an AJAX call, which means you're basically creating a webservice.

or retrieve the value via an AJAX call, which means you're basically creating a webservice.

回答by Fosco

You could output it as part of the page in a script tag... i.e.

You could output it as part of the page in a script tag... i.e.

<script type="text/javascript">
<?php
echo "var sr2 = \"" . $sr2 . "\"";
?>
</script>

Then your jQuery line would be able to access it:

Then your jQuery line would be able to access it:

$('#a2_bottom_' + sr2)

回答by Evan Mulawski

Assuming your jQuery is in the same file:

Assuming your jQuery is in the same file:

... $('#a2_bottom_<?php echo $sr2 ?>') ...