getJSON and OAuth Token


getJSON and OAuth Token

我正在编写一个使用jQuery (getJSON)从PHP页面回调值的脚本。PHP页面正确地显示具有正确键和值的编码对象,这些值是从$_SESSION变量中检索的。然而,当javascript试图访问此页面时,对象被检索,但只有键是完整的,值被替换为null。返回null的值是从$_SESSION中检索的,而手动添加的任何值都正确返回。这是可以避免/解决的问题吗?将访问令牌存储在cookie中比存储在会话中更有意义吗?

代码示例:

<?php
  session_start();
  $token = $_SESSION['token'] -> access_token;
  $information = [
     "media_token" => $token,
     "test" => "testing"
     ]; 
  print json_encode($information); //when page is directly accessed, 
                                   //returns correct information
?>
Javascript:

$.getJSON('oauth.php', function (data){
            console.log(data); // media_token: null
                               // test: testing
    });

原来的问题是,我正在访问包含使用非www页面的JS页面,而添加www修复了这个问题。不知道为什么,但很明显,如果页面可以访问$_SESSION或不。如果有人能解释一下为什么会这样,那就太好了,干杯。

试试这段代码,它会帮助你

<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
$(document).ready(function() {
$.getJSON('oauth.php', function (data){
            console.log(data); // media_token: null
                               // test: testing
    });
});
</script>
</head>
<body>
<div class="title">
    <h2>PRESS</h2>
    <p>hello</p>
</div>
</body>
</html>

oauth.php文件

 session_start();
  $_SESSION['token']="Hello1212";
  $token = $_SESSION['token'];// -> access_token;
  $information = array(
    "media_token" => $token,
    "test" => "testing"
);
  print json_encode($information); //when page is directly accessed, 
                                   //returns correct information