简体   繁体   中英

Use a PHP variable in JQuery

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

Example:

  • PHP variable: $sr2
  • Excerpt of JQuery script (with variable): $('#a2_bottom_$sr2')

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

Thanks

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, eg

<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.

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

<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 -

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

Now your phpVariable is available to your 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 -

<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:

$('#a2_bottom_' + sr2)

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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