php变量不可用

时间:2018-10-31 11:20:31

标签: php html

我使用JQuery Ajax从PHP Steamauth文件中调用会话变量,但是它不起作用, 用此代码(贝洛),当我替换“ $ data ['test'] = $ _SESSION ['steamid'];”时,到“ $ data ['test'] =” ok“;”,效果很好,但是使用初始代码,没有弹出任何警报窗口,并且div(ok)仍设置为'...'。

我不知道为什么无法设置$ _SESSION ['steamid']变量。 非常感谢

test.php:

<?php

header('Content-Type: application/json');
require ('steamauth/steamauth.php');
$data = array();
if(!isset($_SESSION['steamid'])) {
    $data['retour'] = "ok";
    $data['test'] = $_SESSION['steamid'];
    echo json_encode($data);
} else {
    include ('steamauth/userInfo.php');
    $data['retour'] = "not ok";
    echo json_encode($data);
}      
?>

和main.html:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $.get("test.php", function(data, status){
            alert(data.retour);
            document.getElementById('ok').innerHTML = data.test;
        });
    });
});
</script>
</head>
<body>

<button>clic</button>
<div id='ok'>...</div>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

首先,您需要在test.php中启动会话

<?php

session_start(); //HERE SESSION IS STARTED

header('Content-Type: application/json');
require ('steamauth/steamauth.php');
$data = array();
$_SESSION['steamed']='WHAT EVER YOU WANT';
if(!isset($_SESSION['steamid'])) {
    $data['retour'] = "ok";
    $data['test'] = $_SESSION['steamid'];
    echo json_encode($data);
} else {
    include ('steamauth/userInfo.php');
    $data['retour'] = "not ok";
    echo json_encode($data);
} 
?>

输出应为

[{retour: ok},{test: WHAT EVER YOU WANT}]