使用php echo设置javascript变量不起作用

时间:2014-03-11 05:28:29

标签: javascript php

如何将session['user_id']传递给javascript? 我在体内尝试var user_id = "<?php echo session['user_id']; ?>";,但它没有从php收到。

<?php session_start(); 

if(isset($_SESSION['user_id'])){
    //user logged in = true;
    $user_id = $_SESSION['user_id'];
?>

<body>logged in content</body>
//I put my js here


<?php 
}else{
    header('Location: fblogin.php');
    //echo "not logged in";
}
?>

2 个答案:

答案 0 :(得分:0)

在你的js中添加如下:

<script>
  var user_id="<?php echo $user_id; ?>";
 </script>

答案 1 :(得分:0)

这是我使用的jQuery,(在两部分测试中)。 然而正如评论中所述,如果您还没有这样做,请确保您的JS包含在<script>...</script>中。

第1部分(从表单输入设置会话名称)

<?php
ob_start();
session_start();

if(isset($_POST['submit'])){

$_SESSION['myusername'] = $_POST['myusername'];
$_SESSION['mypassword'] = $_POST['mypassword'];

echo $_SESSION['myusername'];
echo "<br>";

echo $_SESSION['mypassword'];

} // isset submit

ob_end_flush();
?>

<form action="" method="post">
Username: 
<input type="text" name="myusername">
<br>
Password: 
<input type="text" name="mypassword">
<br>
<input type="submit" name="submit" value="Submit">
</form>
<br><br>
<a href="sessions_test.php">check session name</a>

第2部分(查看会话名称,如果已设置)(sessions_test.php),在查看HTML源时确实会显示会话名称。

<?php
session_start();
if (isset( $_SESSION['myusername']) && isset( $_SESSION['mypassword']) ){

$myusername = $_SESSION['myusername'];
$mypassword = $_SESSION['mypassword'];

echo $myusername;
echo "<br>";
echo $mypassword;
}
?>

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>

<script>
    $(document).ready(function(){
var player = "<?php echo $_SESSION['myusername']; ?>";

// alert (player);

    });
</script>