duancong7573
2018-06-24 07:55
浏览 59

将PHP变量回送到JavaScript变量中会在HTML中打印PHP变量

I have a HTML page with a script tag with PHP in it as follows:

<div id="myName">
<script type="text/javascript">
   var myName = <?php
   if(isset($_SESSION['name']) && $_SESSION['name'] != ''){
       echo $_SESSION['name'];
   }
   else
       echo "NotSet";
   ?>;
document.write(myName);
</script>
</div>

But running this actually prints like below:

<div id="myName">
    var myName=SomeName;
    document.write(myName);
</div>

Expected:

<div id="myName">
    SomeName
</div>

On doing inspect element:

<div id="myName">
<script type="text/javascript">
    "var myName=SomeName;
    document.write(myName);"
</script>
</div>

I want to post-process the variable myName and derive other values ahead in JS logic. So, I need to get the php value in JS variable.

Please note: I am not asking how to get a PHP variable into JS variable (for which there are many different questions on Stack Overflow). This is a different question and hence not a duplicate for those questions.

图片转代码服务由CSDN问答提供 功能建议

我有一个带有PHP标签的HTML页面,如下所示:

 &lt; div id =“myName”&gt; 
&lt; script type =“text / javascript”&gt; 
 var myName =&lt;?php 
 if(isset($ _ SESSION ['name'  ])&amp;&amp; $ _SESSION ['name']!=''){
 echo $ _SESSION ['name']; 
} 
 else 
 echo“NotSet”; 
?&gt ;; \  ndocument.write(myName); 
&lt; / script&gt; 
&lt; / div&gt; 
   
 
 

但是运行它实际打印如下: <前> &lt; div id =“myName”&gt; var myName = SomeName; document.write(myName); &lt; / div&gt;

预期:

 &lt; div id =“myName”&gt; 
 SomeName 
&lt; / div&gt; 
   
 
 

在执行检查元素时:

 &lt; div id =“myName”&gt; 
&lt; script type =“text / javascript”&gt  ; 
“var myName = SomeName; 
 document.write(myName);”
&lt; / script&gt; 
&lt; / div&gt; 
   
 
 

我想要 后处理变量myName并派生出来 JS逻辑中的r值。 所以,我需要在JS变量中获取php值。

请注意:我不是在问如何将PHP变量转换为JS变量(在堆栈上有很多不同的问题) 溢出)。 这是一个不同的问题,因此对于这些问题,不重复

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • dongzhong8691 2018-06-24 08:21
    已采纳

    You could assign the PHP data as a JavaSscript variable like this - it will be available for further client side processing as desired and you can update the DOM to reflect the content using standard methods.

    <html>
        <head>
            <title>php & js vars</title>
        </head>
        <body>
        <div id='myName'>
            <script>
                <?php
                    printf( 'var myName="%s";', !empty( $_SESSION['name'] ) ? $_SESSION['name'] : 'NotSet' );
                ?>
                document.getElementById('myName').innerHTML=myName;
                alert( myName );// var still available...
            </script>
        </div>
        </body>
    </html>
    

    Update

    The above snippet was written in haste with little thought given to the various ways in which it could break, but to accommodate for double quotes you could make use of htmlentities

    <?php
        session_start();
        $_SESSION['name']='Geronimo"s Revenge';
    ?>
    <html>
        <head>
            <title>php & js vars</title>
        </head>
        <body>
        <div id='myName'>
            <script>
                <?php
                    printf( 'var myName="%s";', !empty( $_SESSION['name'] ) ? htmlentities( $_SESSION['name'], ENT_QUOTES   ) : 'NotSet' );
                ?>
                document.getElementById('myName').innerHTML=myName;
            </script>
        </div>
        </body>
    </html>
    
    已采纳该答案
    打赏 评论
  • dops57958 2018-06-24 08:08

    Why not just use this?

    <div id="myName">
       <?php
       if(isset($_SESSION['name']) && $_SESSION['name'] != ''){
           echo $_SESSION['name'];
       }
       else
           echo "NotSet";
       ?>;
    </div>
    
    打赏 评论
  • duancaiyi7567 2018-06-24 08:12

    If your code is

    <div id="myName">
    <scrpit type="text/javascript">
       var myName = <?php
       if(isset($_SESSION['name']) && $_SESSION['name'] != ''){
           echo $_SESSION['name'];
       }
       else
           echo "Not Set";
       ?>;
    </script>
    </div>
    

    Then the expected result can only be

    <div id=" myName">
        <script type="text/javascript">
            var myName = RESULT OF PHP CODE HERE
        </script>
    </div>
    

    If you want the expected output as described in your question, change your HTML/php to

    <div id="myName">
       <?php
       if(isset($_SESSION['name']) && $_SESSION['name'] != ''){
           echo $_SESSION['name'];
       }
       else
           echo "Not Set";
       ?>;
    </div>
    

    EDIT

    After posting I saw the comments on another answer. You want to use the variable in two places so you have to store the result of your php logic somewhere if the name session variable doesn't change and/or make a function to get it if it can change.

    For one such example

    <?php
        function getNameFromSession() {
            if(isset($_SESSION['name']) && $_SESSION['name'] != ''){
                return $_SESSION['name'];
           }
           else
                return "Not Set";
        }
    
        $myName = getNameFromSession();
    ?>
    
    <div id=" myName">
        <?php echo $myName; ?>
        <script type="text/javascript">
            var myName = "<?php echo $myName; ?>";
        </script>
    </div>
    

    Note that in any case your script would probably be better off in the element.

    打赏 评论
  • dongyao5186 2018-06-24 08:29
    <div id="myName">
    
    </div>
    
    <scrpit type="text/javascript">
       <?php
       if(isset($_SESSION['name']) && $_SESSION['name'] != ''){ ?>
           var myName =<?php echo $_SESSION['name'];?> ;
       <?php }
       else{
      ?>
          var myName = "NotSet";
       <?php } ?>;
      document.getElementById("myName").innerHTML=myName ;
    
    document.write(myName);
    </script>
    
    打赏 评论

相关推荐 更多相似问题