如何在外部 javascript 中从 php 访问会话变量

我知道以前有人问过这个问题,但从头到尾都没有解释。我有一个login.php我想从中获得$_SESSION['user_id']



<?php

include "connect.php";


session_start();


$email=$_POST['email'];

$password=$_POST['password'];


$select_data=mysql_query("select * from user where email='$email' and password='$password'");


if(isset($_POST['email']))

{

if($row=mysql_fetch_array($select_data))

 {

  $_SESSION['user_id']=$row['id']; //The variable want to access from ext.js


  echo "success";

 }

 else

 {

  echo "fail";

 }

 exit();

}

?>

顺便说一句,这种身份验证工作正常


我的主.php



<!DOCTYPE html>

<?php include 'connect.php';

session_start();

echo $_SESSION['user_id']; //works fine

//;

?>

<body>

//contents

<script src="login.js"></script>

<script src="postad.js"></script> //the script from which I want to get $SESSION_['user_id']


</body>

我希望这个变量稍后插入到数据库中。有什么建议?


HUWWW
浏览 126回答 2
2回答

慕虎7371278

如果要在外部 js 文件中调用 php 变量,则必须将值存储在输入中。主文件<body><input type="hidden" value="$SESSION_['user_id']" class="user_id"><script src="login.js"></script><script src="postad.js"></script> //the script from which I want to get $SESSION_['user_id']</body>postad.js$(function(){&nbsp; &nbsp; var user_id = $('.user_id').val();&nbsp; &nbsp; alert(user_id);});如果你想在同一个文件中使用,那么你可以直接使用 php echo。主文件<body>&nbsp; &nbsp; //content..<script>&nbsp; &nbsp; var user_id = "<?php echo $SESSION_['user_id'] ?>";</script><script src="login.js"></script><script src="postad.js"></script> // console.log(user_id); that file you'll get that id.</body>

侃侃尔雅

您可以将会话 ID 值分配给 JavaScript 变量以使其可用于 JavaScript:<!DOCTYPE html><?php include 'connect.php';session_start();echo $_SESSION['user_id']; //works fine//;?><body>//contents<script>&nbsp; &nbsp; var sessionId = "<?php echo $_SESSION['user_id'] ?>";</script><script src="login.js"></script><script src="postad.js"></script> // "sessionId" variable should be available for the script</body>&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP