简体   繁体   English

JavaScript“文本更改onclick”中的PHP变量

[英]PHP variable inside a JavaScript “text change onclick”

Hi I have this JavaScript code inside a PHP echo嗨,我在 PHP echo 中有这个 JavaScript 代码

        function change_text()
            {
                if(document.getElementById(\"toggle_button\").innerHTML==\"Ver respuesta\")
                {
                    document.getElementById(\"toggle_button\").innerHTML=\"$PHP_VARIABLE\";
                }
                else
                {
                    document.getElementById(\"toggle_button\").innerHTML=\"Ver respuesta\";
                }
            }

I need to insert the text of $PHP_VARIABLE at $PHP_VARIABLE, but it is not working... I think this will work with this javascript code who obtain the variable, but I don't know how to insert this in the code.我需要在 $PHP_VARIABLE 处插入 $PHP_VARIABLE 的文本,但它不起作用......我认为这将适用于获取变量的 javascript 代码,但我不知道如何在代码中插入它。

var php_var = "<?php echo $php_var; ?>";

It's exactly as the second code block you showed;它与您展示的第二个代码块完全一样; you need to echo your variable.你需要回应你的变量。

Remember that what leaves your server is not PHP, it's text.请记住,离开您的服务器的不是 PHP,而是文本。 Javascript, from the server point of view, is just text, no different than HTML.从服务器的角度来看,Javascript 只是文本,与 HTML 没有区别。 You can echo out whatever you want, and it doesn't care.你可以回显任何你想要的,它不在乎。 So if you want to embed a variable PHP generates into Javascript, print it out somehow, via echo, print, or some other format.因此,如果您想将 PHP 生成的变量嵌入到 Javascript 中,请通过 echo、print 或其他格式以某种方式将其打印出来。 Once it leaves your server, it's just text, and it's up to the client to interpret the javascript.一旦它离开您的服务器,它就只是文本,由客户端来解释 javascript。

Assuming you have a php echo as this you should simply concat the php var假设你有一个 php echo,你应该简单地连接 php var

<?php  

  echo '<script>
        function change_text()
        {
            if(document.getElementById("toggle_button").innerHTML=="Ver respuesta")
            {
                document.getElementById("toggle_button").innerHTML="' . $PHP_VARIABLE . '";
            }
            else
            {
                document.getElementById("toggle_button").innerHTML="Ver respuesta";
            }
        }
  </script>'; 

?>
function change_text()
    {
        if(document.getElementById("toggle_button").innerHTML=="Ver respuesta")
        {
            document.getElementById("toggle_button").innerHTML="<?php echo $PHP_VARIABLE;?>";
        }
        else
        {
            document.getElementById("toggle_button").innerHTML="Ver respuesta";
        }
    }

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

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