如何从JavaScript中的php文件读取会话变量 [英] How to read a session variable from a php file in JavaScript
问题描述
关于这个主题的问题太多了,但我仍然听不懂.
There have been far too many questions on this subject but I still fail to understand.
案例:
- 超链接图片
- 点击图片:检查会话是否存在
- 如果存在会话,请打开链接
- 如果会话不存在,请显示登录表单
onclick
正在调用JavaScript函数:
onclick
is calling a JavaScript function:
var my_global_link = '';
var check = '<?php echo $_SESSION["logged_in"]; ?>';
function show_login( link ) {
if(check == 1)
{
window.location = link;
}
else
{
my_global_link = link;
// .. then show login modal that uses 'js/whitepaper-login.js'
document.getElementById('light').style.display='block';
document.getElementById('fade').style.display='block';
document.getElementById('fade').scrollIntoView(true);
}
}
全局变量被另存为另一个php文件:
Global variable is being saved in another php file as :
$_SESSION['logged_in'] = 1;
我无法捕获var check
中的会话值.你能建议吗?
I am unable to capture the session value in the var check
. Can you advise?
推荐答案
在这里使用jQuery是一个简单的示例,说明如何将PHP $_SESSION
放入JavaScript:
Using jQuery here is a simple example of how to get a PHP $_SESSION
into your JavaScript:
session.php
session.php
<?php
session_start();
$_SESSION['foo'] = 'foo';
echo $_SESSION['foo']; // this will be echoed when the AJAX request comes in
?>
get_session.html(假定包含jQuery)
get_session.html (assumes jQuery has been included)
<script>
$(function() {
$('a').click(function(event){ // use instead of onclick()
event.preventDefault(); // prevents the default click action
// we don't need complex AJAX because we're just getting some data
$.get('session.php', function(sessionData) {
console.log( sessionData ); // session data will be 'foo'
});
});
});
</script>
<a href="session.php">click</a>
如果成功,您将看到数据,并通过适当地传递数据将其用于其他JavaScript函数.我经常发现json_encode()
会话数据很方便,它返回了供JavaScript使用的JSON,但是在这样的简单示例中就没有必要了.
If this is successful you'll see the data and can use it in other JavaScript functions by passing the data appropriately. I often find it handy to json_encode()
session data, returning JSON to be used by JavaScript, but there is no need to in a simple example such as this one.
这篇关于如何从JavaScript中的php文件读取会话变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!