简体   繁体   English

在JQuery中使用PHP变量

[英]Use a PHP variable in JQuery

Is there anyway I can use a php variable in the JQuery script? 无论如何我可以在JQuery脚本中使用php变量吗?

Example: 例:

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

How can I make it so the variable is valid in that JQuery part? 我怎样才能使变量在JQuery部分中有效?

Thanks 谢谢

PHP runs on the server, jquery runs on the client. PHP在服务器上运行,jquery在客户端上运行。 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, eg 如果你想让一个PHP变量可用于jquery(以及扩展名,底层的javascript引擎),你必须在服务器上输出页面时发送变量的值,例如

<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. 或通过AJAX调用检索值,这意味着您基本上创建了一个Web服务。

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 phpVariable is available to your JavaScript! 现在您的phpVariable可用于您的JavaScript! So you use it like you would in any other case - 所以你像在任何其他情况下一样使用它 -

$("div."+phpVariable);

That will retrieve us any <div> element with a foo class - 这将检索我们任何带有foo类的<div>元素 -

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

You could output it as part of the page in a script tag... ie 您可以在脚本标记中将其作为页面的一部分输出...即

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

Then your jQuery line would be able to access it: 然后你的jQuery行就可以访问它了:

$('#a2_bottom_' + sr2)

假设你的jQuery在同一个文件中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM