简体   繁体   English

将javascript嵌入php代码

[英]Embedding javascript within php code

I have embedded some javascript within php code. 我已经在php代码中嵌入了一些JavaScript。 This was necessary after checking some php session variable value, and upon result, I use some JS within php to decide if some elements will be shown or not. 在检查了一些php会话变量值之后,这是必要的,并且根据结果,我在php中使用了一些JS来决定是否显示某些元素。 Here is an example: 这是一个例子:

<?php

if ($_SESSION['myVar']==2)
      { echo '<script type="text/javascript" >

          document.getElementById("element1").style.visibility = "hidden";
         document.getElementById("element2").style.visibility = "hidden";

            </script>';
?>

The code works perfect for me. 该代码对我来说很完美。 My question is : is the JS executed at the webserver(since it is embedded within php code) , initializing the page before it is sent to the client browser (and that what I think), or does the php portion run at the server, and the JS runs at the client later?? 我的问题是:JS是在Web服务器上执行(因为它已嵌入php代码中),是在将页面发送到客户端浏览器之前初始化页面(以及我的想法),还是php部分在服务器上运行, JS稍后在客户端运行??

I know in normal situations the JS runs at the client browser,but was suspicious in this case, 我知道一般情况下JS是在客户端浏览器上运行的,但在这种情况下却很可疑,

I'm a junior programmer and any help is appreciated, thanks in advance. 我是一名初级程序员,在此先感谢您的帮助。

Javascript is always executed in the browser of the client. Javascript 总是在客户端的浏览器中执行。 The php code just inserts the javascript code as a block of text and the browser reads it as code. php代码只是将javascript代码作为文本块插入,浏览器将其作为代码读取。

不管怎样,JavaScript都是在客户端执行的,但是您只是在PHP代码中插入了代码,以使浏览器可以执行它。

Php sends the JavaScript back to the Client as a response and then on the Client side JavaScript is run. Php将JavaScript作为响应发送回客户端,然后在客户端运行JavaScript。 Please read this ANSWER 123 and you might have a better explanation >> PHP & Embedded JavaScript Behavior . 请阅读此ANSWER 123,您可能会有更好的解释>> PHP和嵌入式JavaScript行为 Thanks 谢谢

<?php

if ($_SESSION['myVar']==2)
      { 
?>
<script type="text/javascript" >
      document.getElementById("element1").style.visibility = "hidden";
         document.getElementById("element2").style.visibility = "hidden";
</script>
<?php } ?>

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

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