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条)

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题