dooso0594 2014-07-31 22:07
浏览 41
已采纳

在JavaScript中使用PHP变量

I'm pretty new, so go easy. I am using a session in PHP with a few variables. I want to concatenate two strings together from my PHP session when the clicks a button. I am using JavaScript onclick to try and achieve this.

I am having trouble getting my JavaScript to accept my PHP variables. Does anybody have any suggestions?

PHP:

$_SESSION['user1'] = $_POST['user'];
$_SESSION['string3'] = $_POST['string1'];
$_SESSION['string4'] = $_POST['string2'];

echo $_SESSION['user1'];
echo $_SESSION['string3'];
echo $_SESSION['string4'];

if(isset($_SESSION['user1'])) {
    echo 'Welcome, '.$_SESSION['user1'].". Lets concatenate ".$_SESSION['string3']." and ".$_SESSION['string4'];

} else {
    echo "<meta http-equiv=\"refresh\" content=\"0;URL=">";
}


<button onclick="xy()">Try it</button>
<p id="answer"></p>

JS:

<script type="text/javascript">
function xy() {
    var x = "<?php $_SESSION['string3']; ?>";
    var y = "<?php $_SESSION['string4']; ?>";
    document.getElementById("answer").innerHTML = x + y;
}
</script>
  • 写回答

2条回答 默认 最新

  • duan_88598 2014-07-31 22:12
    关注

    You need to echo the PHP variable there because otherwise they output nothing and the JS variable ends up empty:

    var x = "<?php echo $_SESSION['string3']; ?>";
    var y = "<?php echo $_SESSION['string4']; ?>";
    

    So for example, if $_SESSION['string3'] is "abc", PHP will echo the value inside the JS and you'll get this:

    var x = "abc";
    

    instead of:

    var x = ""; // no output from PHP when there's no echo
    

    To simplify things, here is your whole function:

    <script type="text/javascript">
    function xy() {
        var x = "<?php echo $_SESSION['string3']; ?>";
        var y = "<?php echo $_SESSION['string4']; ?>";
        document.getElementById("answer").innerHTML = x + y;
    }
    </script>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改