在 jQuery 中获取 PHP 变量

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

Getting a PHP variable in jQuery

phpjquery

提问by tetris

So I have this:

所以我有这个:

<?php
 echo '
  <script>
$(function(){
   $("a#yeah").click(function(){
           $.ajax({
        url: "ajax.php?action=yeah&id='.$id.'",
        success: function(html){
         $("a#yeah").html("your cool")
                   }
     })
   })


})</script>';

?>

basically I am using the PHP variable $id wich can be find in the document, how could i get this same variable but without echoing the jQuery(so i could keep my editor syntax highlight in the Javascript part)?

基本上我正在使用可以在文档中找到的 PHP 变量 $id ,我怎么能得到这个相同的变量但不回显 jQuery(所以我可以在 Javascript 部分保持我的编辑器语法高亮)?

回答by Your Common Sense

never echo any client side code - just type it as is.
PHP especially good in this http://www.php.net/manual/en/language.basic-syntax.phpmode.php

从不回显任何客户端代码 - 只需按原样键入即可。
PHP 在这方面特别好http://www.php.net/manual/en/language.basic-syntax.phpmode.php

  <script>
$(function(){
   $("a#yeah").click(function(){
           $.ajax({
        url: "ajax.php?action=yeah&id=<?php echo $id?>",
        success: function(html){
         $("a#yeah").html("your cool")
                   }
     })
   })


})</script>

回答by Dani

You can add the php inline like:

您可以添加 php 内联,如:

<script> var yourVariable = '<?php echo $phpVar; ?>'; </script>

回答by Ken Redler

Just echo around the variable, as that appears to be the only piece requiring processing:

只需在变量周围回显,因为这似乎是唯一需要处理的部分:

      ...stuff...
      url: "ajax.php?action=yeah&id=<?=$id?>",
      ...more stuff...

If your server doesn't have short_open_tagenabled, then <?php echo $id; ?>

如果您的服务器没有short_open_tag启用,那么<?php echo $id; ?>