简体   繁体   English

如何在JavaScript函数中传递全局变量

[英]How to pass global variable in javascript function

Let say I have a $_SESSION['password'] and a javascript function. 假设我有一个$ _SESSION ['password']和一个javascript函数。

Here's the javascript function: 这是javascript函数:

<script>  
    function check() {
        var password = '<?php echo $_SESSION; ?>';
        alert(password);
        if (document.FormName.password.value != password)
            alert("password does not match");
    } 
</script>

<html>
//form here
</html>

How come when the alert pop-ups, it will only display nothing? 当警报弹出时,为什么什么也不显示呢? what happened? 发生了什么? Is my passing of variable wrong at all? 我的变量传递完全错误吗?

$_SESSION is an array and this will return blank if you echo it. $_SESSION是一个数组,如果您回显它,它将返回空白。

You should use the 您应该使用

<?php echo $_SESSION['password']; ?>

It will echo the password that store in Session. 它将回显存储在会话中的密码。

<script>
    function check() {    
        var password = "<?=$_SESSION['password']?>";//you forgot ['password'] here       
        alert(password);
        if(document.FormName.password.value != password)
            alert("password does not match");
    } 
</script>

<html>
//form here
</html>

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

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